用javascript getComputedStyle获取和设置style的原理
2008-10-10 21:55
513 查看
有兴趣的朋友搜索"百度 popup"就好了,已经有人给出了注释,强大。
最有意思的是用javascript获取和设置style
DOM标准引入了覆盖样式表的概念,当我们用document.getElementById("id").style.backgroundColor 获取样式时 获取的只是id中style属性中设置的背景色,如果id中的style属性中没有设置background-color那么就会返回空,也就是说如果id用class属性引用了一个外部样式表,在这个外部样式表中设置的背景色,那么不好意思document.getElementById("id").style.backgroundColor 这种写法不好使,如果要获取外部样式表中的设置,需要用到window对象的getComputedStyle()方法,代码这样写window.getComputedStyle(id,null).backgroundColor
但是兼容问题又来了,这么写在firefox中好使,但在IE中不好使
两者兼容的方式写成
window.getComputedStyle?window.getComputedStyle(id,null).backgroundColor:id.currentStyle["backgroundColor"];
如果是获取背景色,这种方法在firefox和IE中的返回值还是不一样的,IE中是返回"#ffff99"样子的,而firefox中返回"rgb(238, 44, 34) "
值得注意的是:window.getComputedStyle(id,null)这种方式不能设置样式,只能获取,要设置还得写成类似这样id.style.background="#EE2C21";
最有意思的是用javascript获取和设置style
DOM标准引入了覆盖样式表的概念,当我们用document.getElementById("id").style.backgroundColor 获取样式时 获取的只是id中style属性中设置的背景色,如果id中的style属性中没有设置background-color那么就会返回空,也就是说如果id用class属性引用了一个外部样式表,在这个外部样式表中设置的背景色,那么不好意思document.getElementById("id").style.backgroundColor 这种写法不好使,如果要获取外部样式表中的设置,需要用到window对象的getComputedStyle()方法,代码这样写window.getComputedStyle(id,null).backgroundColor
但是兼容问题又来了,这么写在firefox中好使,但在IE中不好使
两者兼容的方式写成
window.getComputedStyle?window.getComputedStyle(id,null).backgroundColor:id.currentStyle["backgroundColor"];
如果是获取背景色,这种方法在firefox和IE中的返回值还是不一样的,IE中是返回"#ffff99"样子的,而firefox中返回"rgb(238, 44, 34) "
值得注意的是:window.getComputedStyle(id,null)这种方式不能设置样式,只能获取,要设置还得写成类似这样id.style.background="#EE2C21";
您可能感兴趣的文章:
相关文章推荐
- 用javascript getComputedStyle获取和设置style的原理
- JavaScript获取HTML元素样式的方法(style、currentStyle、getComputedStyle)
- Javascript获取CSS属性值getComputedStyle和currentStyle
- javascript 获取样式表里的属性值 currentStyle 和 getComputedStyle 的使用
- javascript的getComputedStyle方法获取节点的计算后的CSS样式
- Javascript获取CSS属性值getComputedStyle和currentStyle
- javascript/dom:获取CSS值/getComputedStyle方法
- javascript获取元素CSS值window.getComputedStyle
- javascript的样式获取--getComputedStyle、currentStyle、style
- js用currentStyle和getComputedStyle获取css样式(非行间)
- getComputedStyle与currentStyle获取样式(style/class)
- 转贴:获取元素CSS值之getComputedStyle方法熟悉
- js中style,currentStyle和getComputedStyle的区别以及获取css操作方法
- Chrome(12)中使用getComputedStyle获取透明度(opacity)返回字符串不同于其它浏览器
- getComputedStyle与currentStyle获取样式(style/class)
- 获取元素的固定位置getComputedStyle(一)css样式表
- JS获取CSS样式(style/getComputedStyle/currentStyle)
- getComputedStyle js获取计算后的style
- 封装getStyle (获取样式currentStyle getComputedStyle兼容处理)