hi, 欢迎访问我的博客

JS获取对象在内存中计算后的样式

  通过obj.style的方式只能取得"内联style"的值,对于<style></style>中的css属性值,则无能为力 。

我们可以用obj.currentStyle,window.getComputedStyle()来获取

意: 只有 IE Opera 支持使用 currentStyle 获取 HTMLElement 的计算后的样式, 其他浏览器中不支持。

标准浏览器中使用getComputedStyleIE9及以上也支持getComputedStyle

window.getComputedStyle(obj,伪元素)
参数说明:
第一个参数为要获取计算后的样式的目标元素
第二个参数为期望的伪元素, 如 ':after'':first-letter' ,一般设为null

考虑兼容性,封装函数
function getStyle (el,attr){
return el.currentStyle?el.currentStyle[attr]:getComputedStyle(el,null)[attr];
}
注意: 2个方法,获取的对象是只读,要改样式,还得靠obj.style

posted @ 2017-07-27 22:10  打静爵  阅读(1231)  评论(0编辑  收藏  举报