获取元素属性值的兼容写法,兼容ie7+,火狐,谷歌

html

<div id="box"></div>

css

#box{
     width: 200px;
     height: 200px;
     border:3px solid #eee;
     position: absolute;
     left:600px;
     top:200px;
}


此时页面上是一个边框为3px的#eee的200px的方形

 


cName为元素的class名或Id名,格式例如:'.box','#box',string
attr为要获取元素的属性名
// 获取元素属性值的兼容写法
function getStyle(cName,attr){
    if(document.querySelector(cName).currentStyle){
        //IE
      console.log(document.querySelector(cName).currentStyle[attr]+'IE');
        return document.querySelector(cName).currentStyle[attr];
    }else{
        //非IE,重点在于ff浏览器需要明确获取的元素属性,例如在google上获取,borderColor 在火狐上就得borderLeftColor
        console.log(getComputedStyle(document.querySelector(cName))[attr]+'非IE');
return getComputedStyle(document.querySelector(cName))[attr];
    }
}

例如:

getStyle('#box','borderWidth');

火狐浏览器打印结果:

 

 谷歌浏览器:

IE10:

 

IE9:

 

 

 IE8:

 

 IE7:

 

 因此在火狐浏览器会出现问题,那是因为火狐浏览器需要详细明确的属性,若是复合属性则不能直接获取到值,所以我们的attr处应该写成‘borderLeftWidth’就各个浏览器都能获取到值了。

posted @ 2019-12-10 14:42  你好,Yvan  阅读(457)  评论(0)    收藏  举报