[读码时间] css函数设置读取对象的属性
说明:代码取自网络,注释为笔者学习时添加!
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>css函数设置读取对象的属性</title> <style> div{ width:400px; height:200px; background:#fef4eb; border:1px solid #f60;/*桔红色*/ margin:0 auto;/*左右置中*/ } input{ border:0; color:#fff; cursor:pointer; font-weight:700; background:#f60; padding:2px 4px; margin:10px 0 0 10px; } </style> <script> function css(obj, attr, value) { switch (arguments.length) { case 2: if (typeof arguments[1] == 'object') {//2个参数,如果第2个参数是对象,批量设置属性 for (var i in attr) obj.style[i] = attr[i]; } else {//2个参数,如果第2个参数是字符串,读取属性值 //currentStyle是ie的属性,ie不支持getComputedStyle方法 //getComputedStyle接收2个参数:要取得计算样式的元素和一个伪元素字符串,如不需要,第2个参数可以是null return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr]; } break; case 3: //3个参数,设置属性值 obj.style[attr] = value; break; default: alert("参数错误!"); } } window.onload = function () { var oBox = document.getElementById("box");//获取div的引用 var aInput = oBox.getElementsByTagName("input");//获取div中所有input元素 aInput[0].onclick = function () { alert("width: " + css(oBox, "width") + "\nheight: " + css(oBox, "height") + "\nbackground-color: " + css(oBox, "backgroundColor")); }; aInput[1].onclick = function () { css(oBox, { width: "330px", height: "100px", borderColor: "#0084ff", backgroundColor: "#eff8ff" }); for (i = 0; i < aInput.length; i++) css(aInput[i], "backgroundColor", "#0084ff"); } aInput[2].onclick = function () { css(oBox, { width: "400px", height: "200px", borderColor: "#f60", backgroundColor: "#fef4eb" }); for (i = 0; i < aInput.length; i++) cancelAnimationFrame(aInput[i], "backgroundColor", "#f60"); } }; </script> </head> <body> <div id="box"> <input type="button" value="Get Style" /><input type="button" value="Set Style" /><input type="button" value="Default Style" /> </div> </body> </html>