getComputedStyle()用法详解

那如果元素即没有在style属性中设置宽高,也没有在样式表中设置宽高,还能用getComputedStyle或currentStyle获取吗?答案是getComputedStyle可以,currentStyle不可以 。

点击查看原文

实际项目中,可能要获取元素的CSS样式属性值,然后再进行其他的操作。

在操作中可能会遇到这种情况,有时候能够正确获取CSS属性值,有时候则不能。

下面通过代码实例分析一下出现这种问题的原因,以及解决方案。

首先看一段代码实例:

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>getComputedStyle使用</title>
<style type="text/css">
div{
    width:100px;
    height:100px;
    margin-top:20px;
}
#first{background-color:red}
</style>
<script type="text/javascript"> 
window.onload=function(){
  var first=document.getElementById("first");
  var second=document.getElementById("second");
  alert(first.style.backgroundColor);
  alert(second.style.backgroundColor);
}
</script>
</head>
<body>
<div id="first"></div>
<div id="second" style="background-color:blue"></div>
</body>
</html>

代码运行后,顺利弹出第二个div的背景颜色,第一个的没有获取到。

不少初学者一开始可能人为dom元素对象的style属性无所不能,不但能设置元素的样式,也能够获取到对应的样式,但它不是万能的,它只能够获取通过style设置的元素CSS属性值:

(1).style内签到HTML标签内设置。

(2).dom.style.width="100px"这样类似设置。

这时getComputedStyle方法的作用就得以体现,它可以获取指定元素对应CSS属性的最终计算值。

语法结构:

window.getComputedStyle(element, [pseudoElt])
 

参数解析:

(1).element:必需,要获取样式值的元素对象。

(2).pseudoElt:可选,表示指定节点的伪元素(:before、:after、:first-line、:first-letter等)。

浏览器支持:

(1).IE9+浏览器支持此方法。

(2).edge浏览器支持此方法。

(3).谷歌浏览器支持此方法。

(4).opera浏览器支持此方法。

(5).火狐浏览器支持此方法。

(6).safria浏览器支持此方法。

代码实例:

 
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>getComputedStyle使用</title>
<style type="text/css">
div{
  width:100px;
  height:100px;
  margin-top:20px;
}
#first{background-color:red}
</style>
<script type="text/javascript"> 
window.onload=function(){
  var first=document.getElementById("first");
  var second=document.getElementById("second");
  alert(window.getComputedStyle(first,null).backgroundColor);
  alert(second.style.backgroundColor);
}
</script>
</head>
<body>
<div id="first"></div>
<div id="second" style="background-color:blue"></div>
</body>
</html>
 

以上代码成功的获取了第一个div的背景颜色。

<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>getComputedStyle使用</title>
<style type="text/css">
div{
  width:100px;
  height:100px;
  margin-top:20px;
}
#first{background-color:red}
#first::before{
  content:"添加的内容";
  color:#0000ff;
}
</style>
<script type="text/javascript"> 
window.onload=function(){
  var first=document.getElementById("first");
  var second=document.getElementById("second");
  alert(window.getComputedStyle(first,":before").color);
}
</script>
</head>
<body>
<div id="first"></div>
<div id="second" style="background-color:blue"></div>
</body>
</html>
 

以上代码可以获取伪元素中字体颜色值(颜色会被转换成RGB或者RGBA模式)。

不能直接获取复合属性值,例如padding属性的值,只能读paddingLeft、paddingTop等属性。

原文地址:https://www.cnblogs.com/taohuaya/p/9978365.html