无法获得DOM元素样式

时间:2018-06-14 20:00:00

标签: javascript

我试图循环一些dom元素并获取它们的颜色,然后将它应用到另一个元素,但是当我这样做时没有任何反应,当我尝试控制日志属性我得到它没有回报。这是我的代码:



var btn = document.getElementsByTagName('button');
var div = document.querySelector('div');

for(i = 0; i < btn.length; i++){
  btn[i].addEventListener('mouseover', function(){
    var col = this.style.backgroundColor;
    console.log(col)
    div.style.backgroundColor = col;
  })
}
&#13;
button:nth-of-type(1){
  background-color:red;
}
button:nth-of-type(2){
  background-color:gold;
}
button:nth-of-type(3){
  background-color:teal;
}
div{
  background-color:lightgrey;
  margin:50px;
}
button, div{
  width:50px;
  height:50px;
}
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <button>1</button>
  <button>2</button>
  <button>3</button>
  <div></div>
</body>
</html>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

那是因为HTMLElement.style.prop检索内联stlye; style属性中的内容。您需要使用Window.getComputedStyle

var btn = document.getElementsByTagName('button');
var div = document.querySelector('div');

for(i = 0; i < btn.length; i++){
  
  btn[i].addEventListener('mouseover', function(){
   
    var computedStyle = window.getComputedStyle(this);
    
    div.style.backgroundColor = computedStyle.backgroundColor;
  
  })

}
button:nth-of-type(1){
  background-color:red;
}
button:nth-of-type(2){
  background-color:gold;
}
button:nth-of-type(3){
  background-color:teal;
}
div{
  background-color:lightgrey;
  margin:50px;
}
button, div{
  width:50px;
  height:50px;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <button>1</button>
  <button>2</button>
  <button>3</button>
  <div></div>
</body>
</html>