DOM基本操作2
读写css属性
dom.style.prop
- 可读写行间样式,没有兼容性问题,碰到float这样的保留字属性,前面应加css
- eg:float --> cssFloat
- 复合属性必须拆解,组合单词变成小驼峰式写法
- 写入的值必须是字符串格式
查询计算样式
window.getComputedStyle(ele,null);
- 计算样式只读
- 返回的计算样式值都是绝对值,没有相对单位
- 其中,第二个参数null一般不用,极少条件下用来获取伪元素的样式
- IE8以及IE8以下不兼容
查询样式
ele.currentStyle
- 计算样式只读
- 返回的计算样式的值不是经过转换的绝对值
- IE独有的属性
封装兼容性方法getStyle(elem,prop)
eg:
<div style="width: 100px; height:100px; background-color:red; position: absolute; left: 0;"></div>
<script type="text/javascript">
function getStyle(elem, prop) {
if (window.getComputedStyle) {
return window.getComputedStyle(elem, null)[prop];
} else {
return elem.currentStyle[prop];
}
}
var div = document.getElementsByTagName('div')[0];
var timer = setInterval(function () {
div.style.left = parseInt(getStyle(div, 'left')) + 1 + 'px';
if(parseInt(div.style.left) == 300){
clearInterval(timer);
}
}, 10);
</script>