交互设计中心-72色

交互设计中心 | 用户体验 | 优化

在css里面写javascript---css expression属性

2009年1月4日 | 分类:DIV+CSS | 评论:0 | 引用:0 | | Tags:expression  javascript  

给元素固有属性赋值
  例如,你可以依照浏览器的大小来安置一个元素的位置。

 

div css xhtml xml Example Source Code Example Source Code [www.52css.com]
#myDiv {
position: absolute;
width: 100px;
height: 100px;
left: expression(document.body.offsetWidth - 110 + “px”);
top: expression(document.body.offsetHeight - 110 + “px”);
background: red;
}


  给元素自定义属性赋值
  例如,消除页面上的链接虚线框。 通常的做法是:

 

div css xhtml xml Example Source Code Example Source Code [www.52css.com]
<a href=”link1.htm” onfocus=”this.blur()”>link1</a>
<a href=”link2.htm” onfocus=”this.blur()”>link2</a>
<a href=”link3.htm” onfocus=”this.blur()”>link3</a>


  粗看或许还体现不出采用expression的优势,但如果你的页面上有几十甚至上百个链接,这时的你难道还会机械式地Ctrl+C,Ctrl+V么,何况两者一比较,哪个产生的冗余代码更多呢?
  采用expression的做法如下:

 

div css xhtml xml Example Source Code Example Source Code [www.52css.com]
<style type=”text/css”>
a {star : expression(onfocus=this.blur)}
</style>
<a href=”link1.htm”>link1</a>
<a href=”link2.htm”>link2</a>
<a href=”link3.htm”>link3</a>


  说明:里面的star就是自己任意定义的属性,你可以随自己喜好另外定义,接着包含在expression()里的语句就是JS脚本,在自定义属性与expression之间可别忘了还有一个引号,因为实质还是CSS,所以放在style标签内,而非s cript内。OK,这样就很容易地用一句话实现了页面中的链接虚线框的消除。不过你先别得意,如果触发的特效是CSS的属性变化,那么出来的结果会跟你的本意有差别。例如你想随鼠标的移进移出而改变页面中的文本框颜色更改,你可能想当然的会认为应该写为

 

div css xhtml xml Example Source Code Example Source Code [www.52css.com]
<style type=”text/css”>
input
{star : expression(onmouseover=this.style.backgroundColor=”#FF0000″;
onmouseout=this.style.backgroundColor=”#FFFFFF”)}
</style>
<style type=”text/css”>
input {star : expression(onmouseover=this.style.backgroundColor=”#FF0000″;
onmouseout=this.style.backgroundColor=”#FFFFFF”)}
</style>
<input type=”text”>
<input type=”text”>
<input type=”text”>


  可结果却是出现脚本出错,正确的写法应该把CSS样式的定义写进函数内,如下所示:

 

div css xhtml xml Example Source Code Example Source Code [www.52css.com]
<style type=”text/css”>
input {star : expression(onmouseover=function()
{this.style.backgroundColor=”#FF0000″},
onmouseout=function(){this.style.backgroundColor=”#FFFFFF”}) }
</style>
<input type=”text”>
<input type=”text”>
<input type=”text”>


  注意:不是非常需要,一般不建议使用expression,因为expression对浏览器资源要求比较高。
  实例:利用css里expression来实现界面对象的批量控制
  问题说明: 用过CSS样式我们就知道, 可以定义一批对象的class属性来指定同一个样式来统一界面. 但如何统一同类型的对象的事件? 比如:界面有无数个 <img src=”**.jpg”> 如何实现鼠标经过此图片, 图片的src变成是**_over.jpg?
  解决方法: 使用css的expression方法,
  具体实现要看看.css的写法:

 

div css xhtml xml Example Source Code Example Source Code [www.52css.com]
/*替换图片CSS*/
#imgScript { /*这里使用对象ID来通配样式, 也可以定义一个css函数*/
star:expression(
onmouseover = function()
{
/*替换图片*/
if(this.hover != null){
this.name = this.src;
this.src = this.src.replace(’.jpg’, ‘_over.jpg’);
this.HasChg = 1;
}
},
onmouseout = function()
{
/*还原本来的图片*/
if(this.HasChg != null){
this.src = this.name;
this.HasChg = null;
}
}
)

}/*end imgScript*/

转自:52css.com

Share
« 72color在这里祝大家元旦快乐表单提交后按钮变灰不可用的方法 »



◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。