我试图循环一些 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/