枯燥的脚本化css

读写元素css属性

dom.style.prop
修改的是行间样式。
可读写行间样式,没有兼容性问题,碰到float这样的保留字属性,前面应该加css。
background-color->backgroundColor
在这里插入图片描述

像border有很多属性:(建议拆解,组合单词变成小驼峰写法)
div.style.borderWidth
div.style.borderStyle

写入值必须是字符串

脚本化CSS

查询计算样式
window.getComputedStyle(ele,null);
伪元素:window.getComputedStyle(div,“after”)[prop]
计算样式只读
返回的计算样式的值
在这里插入图片描述
(看权重问题,这个比div.style.width更准确并且不能修改)

查询样式
ele.currentStyle
计算样式只读
返回的计算样式的值不是经过转换的绝对值
IE独有属性

移动方块demo

<div style="width: 100px; height: 100px; background-color: red; position: absolute;"></div>
<script>
    function getStyle(elem,prop){
    
    
        if(window.getComputedStyle){
    
    
            return window.getComputedStyle(elem,null)[prop];

        }else {
    
    
            return elem.currentStyle[prop];
        }
    }
    var div = document.getElementsByTagName('div')[0];
    setInterval(function(){
    
    
        div.style.left = parseInt(getStyle(div,'left'))+10+'px';
    },100);
</script>

猜你喜欢

转载自blog.csdn.net/weixin_51664705/article/details/114077408