style属性设置和获取

语法:style.属性="属性值";
注意:
1.样式少的时候使用;
2.style是对象;
3.值是字符串,没有设置值是“”;
4.命名规则,驼峰命名。和css不一样;
5.设置了类样式不能获取。(只和行内式交互,和内嵌和外链无关);
6.box.style.cssText = “字符串形式的样式”;
7.style是一个对象,不能获取内嵌和外链。

获取元素样式兼容写法

        function getStyle(ele,attr){
            if(window.getComputedStyle){
                return window.getComputedStyle(ele,null)[attr];
            }
            return ele.currentStyle[attr];
        }

案例:
描述:鼠标经过的的时候,盒子的大小和透明度发生改变
示例代码:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
<div style="width: 100px;height: 100px;background-color: pink;"></div>
<script>

    var div = document.getElementsByTagName("div")[0];
    div.onmouseover = function () {
        div.style.width = "200px";
        div.style.height = "200px";
        div.style.backgroundColor = "black";
        div.style.opacity = "0.2";
        div.style.filter = "alpha(opacity=20)";
    }

</script>

</body>
</html>
Last modification:April 23, 2018
If you think my article is useful to you, please feel free to appreciate