首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法获取DOM元素样式

无法获取DOM元素样式
EN

Stack Overflow用户
提问于 2018-06-15 04:00:00
回答 1查看 39关注 0票数 0

我试图循环一些dom元素并获取它们的颜色,然后将其应用于另一个元素,但是当我这样做时什么也没有发生,并且当我试图通过控制台记录属性时,我得到了它什么也没有返回。下面是我的代码:

代码语言:javascript
复制
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;
  })
}
代码语言:javascript
复制
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;
}
代码语言:javascript
复制
<!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>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-15 04:08:55

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

代码语言:javascript
复制
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;
  
  })

}
代码语言:javascript
复制
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;
}
代码语言:javascript
复制
<!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>

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50865020

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档