规则7 避免CSS表达式
1. CSS表达式:
CSS expressions only work in Internet Explorer
background-color: expression((new Date()).getHours()%2 ?"#B8D4FF" :"#F08A00");
expression方法接受一个JavaScript表达式,CSS属性将被设置为对js表达式进行求值得结果。
expression被其他浏览器忽略,但却是IE浏览器创建跨浏览器有效方法。
IE不支持min-width, 可以这样:
width: expression(document.body.clientWidth<600 ?"600px" :"auto") ;
min-width: 600px;
2. 更新表达式
CSS表达式的问题在于对其求值得频率比人们期望的要高。它们在页面呈现和大小改变时求值,当页面滚动,甚至鼠标上衣过都要求值。
3. 替代方案
a. 一次性表达式
<style>
p { background-color: expression(altBgcolor(this) ; }
</style>
<script type="text/javascript">
function altBgcolor(elem){
elem.style.backgroundColor = (new Date()).getHours()%2 ?"#B8D4FF" :"#F08A00" ;
}
</script>
只在页面呈现时求值;
b. 事件处理器
function setMinWidth(){
var aElements = document.getElementByTagName("p") ;
for(var i = 0; i < aElements.length; i++){
aElement[i].runtimeStyle.width = (document.body.clientWidth<600 ?"600px" :"auto") ;
} // runtimeStyle 是DHTML属性
}
if(-1 != navigator.userAgent.indexOf("MSIE")){
window.onresize = setMinWidth ;
}
这时浏览器在改变大小时会动态的设置宽度,但是页面呈现时不能设置宽度。可以考虑使用一次性表达式。