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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

  2020-05-12 我要评论
有兴趣的朋友搜索"百度 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";

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们