Ruby's Louvre

每天学习一点点算法

导航

CSS Expression用法总结

转自http://www.chencheng.org/demo/css-expression.php

CSS Expression,动态 CSS 属性,IE 私有,自 5.0 开始引入(IE8 将不再支持),参考 MSDN,不过有时用javascript动态生成它作为IE6的hack还是不错的!

这东西的优点:

  • 使 CSS 属性动态生成,所以基本 js 能干的它都能干
  • 使用 CSS 选择符,比 js 遍历到某个特定元素要方便得多

这东西的缺点:

  • expression 会反复执行,有严重的效率问题。它的触发似乎不是通过事件,而是通过 interval 一类的机制。
  • 别的浏览器不支持,IE8 也将不再支持
  1. IE6 的背景闪烁 Bug Fix
    body {
    	zoom: expression(function(el){
    	document.execCommand('BackgroundImageCache', false, true);
    	el.style.zoom = '1';
    	}(this));
    }
    
  2. 给不同 type 的 input 赋予不同的样式
    input {
    	zoom: expression(function(el){
    		el.style.zoom = "1";
    		el.className ? el.className+=" "+el.type : el.className=el.type;
    	}(this));
    }
    
  3. 隔行换色(zebra lists)
    .test {
    	unicode-bidi: expression(function(el){
    		el.style.unicodeBidi = "normal";
    		var childs = el.getElementsByTagName("li");
    		for(var i=0; i<childs.length; i++){
    			(i % 2)?childs[i].className+=" even":childs[i].className+=" odd";
    		}
    	}(this));
    }
    
  4. 模拟 :before 或者 :after
    .test {
    	letter-spacing: expression(function(el){
    		el.style.letterSpacing = "0";
    		var newchild = document.createElement("span");
    		newchild.className="after";
    		newchild.appendChild(document.createTextNode(" World!"));
    		el.appendChild(newchild);
    	}(this));
    }
    
  5. 模拟图片的:max-width 和 max-height (或 min-width 和 min-height)

    .max-width span img {
    	max-width:120px;
    	max-height:120px;
    	zoom:expression(function(el){
    		el.style.zoom = "1";
     
    		var resizeImg = function() {
    			if (el.width > 120 || el.height > 120) {
    				if (el.width > el.height) {
    					el.width = "120";
    					el.height = el.height * (el.width / 120);
    				} else {
    					el.height = "120";
    					el.width = el.width * (el.height / 120);
    				}
    			}
    		}
     
    		if (el.complete) {
    			resizeImg();
    		} else {
    			el.onload = function() {
    				resizeImg();
    			}
    		}
    	}(this));
    }
    
  6. IE6的:hover

    .ie6-hover input:hover, .ie6-hover .h {
    	border:1px solid red;
    }
    .enable-ie6-hover input {
    	_zoom:expression(function(el){
    		el.style.zoom = "0";
    		el.onmouseenter = function() {
    			el.className = "h";
    		};
    		el.onmouseleave = function() {
    			el.className = "";
    		};
    	}(this));
    }
    
  7. IE6下的line-height bug

    bug:

    fixed:

    .ie6-line-height-bug { background:#f2f2f2; line-height:50px; zoom:1; }
    .ie6-line-height-bug-fixed input {
    	_zoom: expression(function(el){
    		el.style.zoom = "1";
    		var iefixer = document.createElement("b");
    		iefixer.style.zoom = 1;
    		el.parentNode.insertBefore(iefixer, el);
    	}(this));
    }
    

posted on 2009-07-29 18:37  司徒正美  阅读(10863)  评论(0编辑  收藏  举报