zoukankan      html  css  js  c++  java
  • js_getComputed方法和style属性关于读取样式的区别

    菜鸟教程:window.getComputedStyle() 方法的使用

    getComputedStyle方法的使用

    • getComputedStyle方法是window对象下的方法,它接收element的值并获取它的最终属性.
        <style>
            .div1 {
                 150px;
                height: 150px;
                background-color: orange;
            }
        </style>
    <body>
        <div class="div1" style="background-color: rgb(150,150,150);"></div>
        <script>
            var $div1 = document.getElementsByClassName('div1')[0];
            console.log(getComputedStyle($div1).backgroundColor);//rgb(150, 150, 150)
            console.log(getComputedStyle($div1).width);//150px
            console.log(getComputedStyle($div1).src);//undefined
            console.log($div1.style.width);//undefined
            console.log($div1.style.backgroundColor);//rgb(150, 150, 150)
        </script>
    </body>
    

    如上代码所示:div1最终显示为一个长150px宽150px的灰色div盒子.

    • 通过getComputedStyle获取的背景色是灰色,style嵌入样式与style内联属性冲突时内联属性优先,getComputedStyle方法返回的是三种属性中最终显示的属性.
    • 未定义的样式属性值为undefined.
    • .style方式只能获取内联属性的值.
    • getComputedStyle方法只能读取,不能写入,.style可以读取也可以写入
    • 兼容性:chromefirefoxIE9 10 11支持
  • 相关阅读:
    算法第四章上机实验报告
    算法第四章作业
    算法第三章上机实验报告
    算法第三章作业
    算法第二章上机实验报告
    算法第二章作业
    第五次c++作业总结
    第三次c++作业总结
    Linux上部署Java项目
    JVM类加载
  • 原文地址:https://www.cnblogs.com/Syinho/p/13197401.html
Copyright © 2011-2022 走看看