无法获取 DOM 元素样式
2018-06-14
41
我尝试循环遍历一些 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>
1个回答
这是因为
HTMLElement.style.prop
检索内联样式;在
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>
Adam Azad
2018-06-14