js基础---正常浏览器与IE获取元素的样式 getComputedStyle/元素.currentStyle

时间:2021-09-06 06:44:28   收藏:0   阅读:38
        - 正常浏览器
            - 使用getComputedStyle()
            - 这个方法是window对象的方法,可以返回一个对象,这个对象中保存着当前元素生效样式
            - 参数:
                1.要获取样式的元素
                2.可以传递一个伪元素,一般传null
            - 例子:
                获取元素的宽度
                    getComputedStyle(box , null)["width"];
            - 通过该方法读取到样式都是只读的不能修改

        - IE8
            - 使用currentStyle
            - 语法:
                元素.currentStyle.样式名
            - 例子:
                box.currentStyle["width"]
            - 通过这个属性读取到的样式是只读的不能修改
 
            window.onload = function(){
                var bx1 = document.getElementById("box1");
                document.querySelector(".btn1").onclick = function(){
                    bx1.style.height = "400px";
                    bx1.style.width = "400px";
                    bx1.style.backgroundColor = "red";
                    
                }
                
                document.querySelector(".btn2").onclick = function(){
                    if(window.getComputedStyle){
                        // 正常浏览器
                        alert(getComputedStyle(bx1,null).backgroundColor);
                    }else{
                        //IE8
                        alert(bx1.currentStyle.backgroundColor);
                    }
                    
                }
            }

 

原文:https://www.cnblogs.com/leiyanting/p/15229315.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!