JavaScript修改与访问CSS
摘要:我们知道JavaScript可以很方便地修改元素的CSS属性。例如我们想要修改x元素的color属性,只需要如下代码就可以了: x.style.color = "blue"; 通过修改元素的style属性即可。唯一需要注意的是形
我们知道JavaScript可以很方便地修改元素的CSS属性。例如我们想要修改x元素的color属性,只需要如下代码就可以了:
x.style.color = "blue";
通过修改元素的style属性即可。唯一需要注意的是形如font-size这种有“-”的CSS属性在JavaScript中需要改写为fontSize。
修改CSS属性简单,但是访问起来就不见得了。我们知道,有多种方式添加CSS样式,而我们使用"x.style.color"并不一定能返回设置在x元素上的color属性。我们需要使用比较复杂一点的方法。
访问元素CSS属性
很不幸,不同的浏览器访问CSS属性的方法并不完全相同。IE中需要使用元素的currentStyle属性;而W3C标准中则使用window的getComputedStyle方法。《ppk谈JavaScript》一书中有如下跨浏览器的函数来获得一个元素的特定CSS属性。
function getRealStyle(id,styleName){ var element = document.getElementById(id); var realStyle = null; if(element.currentStyle){ realStyle = element.currentStyle[styleName]; }else if(window.getComputedStyle){ realStyle = window.getComputedStyle(element,null)[styleName]; } return realStyle; }
我们试验一下用下面的代码来访问当前页面中id为content的div的CSS属性,并且把这些属性显示出来。JavaScript代码如下:
<script type="text/javascript"> function getRealStyle(id,styleName){ var element = document.getElementById(id); var realStyle = null; if(element.currentStyle){ realStyle = element.currentStyle[styleName]; }else if(window.getComputedStyle){ realStyle = window.getComputedStyle(element,null)[styleName]; } return realStyle; } function addEventSimple(obj,evt,fn){ if(obj.addEventListener){ obj.addEventListener(evt,fn,false); }else if(obj.attachEvent){ obj.attachEvent('on'+evt,fn); } } addEventSimple(window,'load',init); function init(){ addEventSimple(document,'click',clickFunc); } function clickFunc(){ var str = ""; str += "color:" + getRealStyle("content","color"); str += "<br />width:" + getRealStyle("content","width"); str += "<br />padding-top:" + getRealStyle("content","paddingTop"); str += "<br />margin-top:" + getRealStyle("content","marginTop"); str += "<br />font-size:" + getRealStyle("content","fontSize"); var watchScreen = document.getElementById("watchScreen"); watchScreen.innerHTML = str; } </script>演示: