读写样式属性
DOM是无法直接操作css样式的,它只是通过操作DOM节点的style属性从而间接操作样式的。
下面是获取元素属性样式的常用方法:
(1)window.getComputedStyle(elem, null)[prop](IE8及以下是不支持的)
(2)document.currentStyle(elem, null)[prop](只有IE兼容并且IE8及以下是支持的)
对兼容性写法的封装:
<style>
div {
width: 10px;
}
</style>
<div>我是直接生成的代码片段</div>
<script>
//我们还是对读取样式属性的兼容性写法进行一个简单的封装吧
function getStyle(elem, property) {
if (window.getComputedStyle) {
if (property) {
return window.getComputedStyle(elem, null)[property];
} else {
return window.getComputedStyle(elem, null);
}
} else {
if (property) {
return document.currentStyle(elem, null)[property];
} else {
return document.currentStyle(elem, null);
}
}
}
let div = document.getElementsByTagName("div")[0];
console.log(getStyle(div, "width"));
console.log(getStyles(div, "after").width);
//而上述方法中的第二个参数是用来获取伪元素的宽高等属性的
</script>