js原生getComputedStyle与currentStyle获取样式(style/class)

js原生getComputedStyle与currentStyle获取样式(style/class)

 

大家都知道,用document.getElementById(‘element’).style.xxx可以获取元素的样式信息,可是它获取的只是DOM元素style属性里的样式规则,对于通过class属性引用的外部样式表,就拿不到我们要的信息了

DOM标准里有个全局方法getComputedStyle,可以获取到当前对象样式规则信息,如:getComputedStyle(obj,null).paddingLeft,就能获取到对象的左内边距。但是事情还没完,万恶的IE不支持此方法,它有自己的一个实现方式,那就是currentStyle,不同于全局方法getComputedStyle,它是作为DOM元素属性存在的,如:obj.currentStyle.paddingLeft,在IE中就获取到对象的左内边距了,兼容性的写法如下:

1
2
3
var oStyle =
this.currentStyle? this.currentStyle : window.getComputedStyle(this, null);
alert(oStyle.height);
  • getComputedStyle是一个可以获取当前元素所有最终使用的CSS属性值。返回的是一个CSS样式声明对象([object CSSStyleDeclaration]),只读。
代码示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js用currentStyle和getComputedStyle获取css样式</title>
<style type="text/css">
#div1{width:100px; height:100px; background:red;}
</style>
<script type="text/javascript">
function getStyle(obj, attr){
if(obj.currentStyle){//IE
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
}

function setStyle(obj,val){
//IE低版本浏览器兼容设置
if(obj.currentStyle){//IE
obj.style.filter = "alpha(opacity="+parseInt(val)+"%)";
}else{
obj.style.opacity = val;
}
}

window.onload=function(){
var oDiv=document.getElementById('div1')
alert(getStyle(oDiv,'width'))
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
getComputedStyle与style的区别
  • 只读与可写
    getComputedStyle方法是只读的,只能获取样式,不能设置;而element.style能读能写,能屈能伸。

  • 获取的对象范围
    getComputedStyle方法获取的是最终应用在元素上的所有CSS属性对象(即使没有CSS代码,也会把默认的祖宗八代都显示出来);而element.style只能获取元素style属性中的CSS样式

getPropertyValue以及getAttribute方法获取元素

getPropertyValue方法可以获取CSS样式申明对象上的属性值(直接属性名称),例如:

1
window.getComputedStyle(element, null).getPropertyValue("float");

兼容 IE6-8

  • 在老的IE浏览器(包括最新的),getAttribute方法提供了与getPropertyValue方法类似的功能,可以访问CSS样式对象的属性。用法与getPropertyValue类似:style.getAttribute(“float”);
  • 就是属性名需要驼峰写法,如下: style.getAttribute(“backgroundColor”);
  • 如果不考虑IE6浏览器,貌似也是可以这么写:style.getAttribute(“background-color”);
代码示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<input type="button" id="button" class="button" value="点击我,显示背景色" />

<script>
var oButton = document.getElementById("button");
if (oButton) {
oButton.onclick = function() {
var oStyle =
this.currentStyle? this.currentStyle : window.getComputedStyle(this, null);
if (oStyle.getPropertyValue) {
alert("getPropertyValue下背景色"+oStyle.getPropertyValue("background-color"));
}else {
alert("getAttribute下背景色:" + oStyle.getAttribute("backgroundColor"));
}
};
</script>
posted @ 2021-03-15 10:40  lianggl  阅读(294)  评论(0)    收藏  举报