模拟封装的类jquery的css函数
这个列子用到了函数不定参(arguments)这个知识点
还有有关样式的一些知识,我们都知道obj.style 可以设置、返回行间的样式
如果非行间样式,用这个就不靠谱了,所以例子中用到了obj.currentStyle 和 getComputedStyle
这两个都是设置、返回计算后的样式的
其中 obj.currentStyle 只有IE才有效
getComputedStyle 在firefox chrome 中有效
废话不说了,上代码
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>模拟封装的类jquery的css函数</title> <style type="text/css"> #test {width:100px; height:100px; background:#ccc;} </style> </head> <body> <input type="button" id="btn1" value="样式"> <div id="test"></div> <script> window.onload = function () { var oBtn = document.getElementById('btn1'); var oTest = document.getElementById('test'); oBtn.onclick = function () { alert(css(oTest, 'width')); css(oTest, 'backgroundColor', '#f00') } } function css(obj, attr, value) { if(arguments.length == 2) { return getStyle(obj, attr); } else if(arguments.length === 3) { obj.style[attr] = value; } } function getStyle(obj, attr) { if(obj.currentStyle) { return obj.currentStyle[attr];//兼容IE浏览器 } else { return getComputedStyle(obj, false)[attr];//兼容firefox chrome } } </script> </body> </html>