javascript - 无法获取 DOM 元素样式

标签 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;
  })
}
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>

最佳答案

这是因为 HTMLElement.style.prop 检索内联 STLye;在 style 属性中找到的内容。您需要使用 Window.getCompulatedStyle

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>

关于javascript - 无法获取 DOM 元素样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50865020/

相关文章:

javascript - 如何将此 Object.values 除以总数?

javascript - 如何用一个函数创建多个 jquery 函数?

javascript - 如何获取多个文本框值?

javascript - 带工具提示的 D3 径向树?

javascript - 通过脚本标签包含 vuex.js 时 Vuex mapState 引用错误

javascript - JS - 从 FireFox 选择子节点时出现问题

java - ReactJS 返回解析器错误 SyntaxError : Unexpected token a after AJAX call to JAVA servlet

javascript - 无法获取在弹出文本框中输入的值

javascript - 使用大量内存的简单功能

javascript - 如何将 firestore 集合转换为有用的对象