ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

js_getComputed方法和style属性关于读取样式的区别

2020-06-27 09:56:02  阅读:312  来源: 互联网

标签:150 style getComputed getComputedStyle js 150px div1 属性


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

getComputedStyle方法的使用

  • getComputedStyle方法是window对象下的方法,它接收element的值并获取它的最终属性.
    <style>
        .div1 {
            width: 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可以读取也可以写入
  • 兼容性:chrome\firefox\IE9 10 11支持

标签:150,style,getComputed,getComputedStyle,js,150px,div1,属性
来源: https://www.cnblogs.com/Syinho/p/13197401.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有