这里先定义一个对象
<style>
#box{
width:100px;
height:100px;
background-color:#ddd;
}
</style>
<div id="box" style="position: absolute;"></div>
获取CSS样式分为两种
一种是获取行内(内联)样式,一种是获取样式表里的样式
1.获取行内样式
对象.style.属性
var box_ele = document.getElementById("box");
console.log(box_ele.style.position;
输出为:
absolute
2.获取样式表里的样式
getConputedStyle(对象)
getComputedStyle();
var style_list = getConputedStyle(box);
console.log(style_list["width"]);
console.log(style_list.width);
输出:
100px
注意,两种方法都可,但是更推荐用上面一种,因为样式里面经常会有带-的属性,比如padding-top
但getComputedStyle()不兼容IE浏览器
IE浏览器的写法:
currentStyle
var style_list = box_ele.currentStyle;
如果对于兼容要求高的写法的话,可以对两种写法进行封装
该方法的逻辑时判断getComputedStyle
在运行是否是一个函数,typeof
返回的是函数,那么说明使用的不是IE浏览器,若返回的是undefind
,那么使用的就是IE浏览器
ele
对象,arrr
要取出的样式
function getStyle( ele , attr ){
if(typeof getComputedStyle === "function"){
return getComputedStyle(ele)[attr];
}else{
return ele.currentStyle[attr];
}
}
var box_ele = document.getElementById("box");
var res = getStyle( box_ele , "width" )
console.log(res);
运行结果:100px