getComputedStyle与style的区别
getComputedStyle有两个参数,第一个参数传元素,第二个元素传伪类,在使用中若不获取伪类,可以把伪类项设置位null,可以避免兼容问题。
1.getComputedStyle是获取元素最终呈现的样式,style只能拿到行内style属性设置的属性,对于类似于的空标签,style拿不到属性,将返回空字符串。
2.getComputedStyle只能获取元素样式,style可以获取和更改。
<div style="margin-top: 1px;" id="box"></div>
var box = document.querySelector('#box');console.log(box.style['margin-top']);//1pxconsole.log(getComputedStyle(box,null)['margin-top']);//1pxconsole.log(getComputedStyle(box,null)['position']);//absoluteconsole.log(getComputedStyle(box,'hover'['backgroundColor']);//rgb(255, 0, 0)console.log(box.style['position']);//''
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
