getcomputedstyle:用javascript getComputedStyle获取和设置style的原理

有兴趣朋友搜索"百度 popup"就好了已经有人给出了注释强大
最有意思是用javascript获取和设置style
DOM标准引入了覆盖样式表概念当我们用document.getElementById("id").style.backgroundColor 获取样式时 获取只是id中style属性中设置背景色如果id中style属性中没有设置background-color那么就会返回空也就是说如果id用属性引用了个外部样式表在这个外部样式表中设置背景色那么不好意思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";
Tags:  javascript获取参数 javascript获取id javascriptstyle getcomputedstyle

延伸阅读

最新评论

发表评论