简体   繁体   English

无法获得DOM元素样式

[英]Can't get DOM element styles

I'm trying to loop over some dom elements and get their color, then apply it to another element, but when I do that nothing happens and when I try to console log the property I'm getting it returns nothing. 我试图遍历一些dom元素并获取它们的颜色,然后将其应用于另一个元素,但是当我这样做时什么也没有发生,并且当我尝试控制台日志属性时,我得到的它不返回任何内容。 Here's my code: 这是我的代码:

 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> 

That's because HTMLElement.style.prop retrieves the inline stlye; 这是因为HTMLElement.style.prop检索了内联样式。 what is found in style attribute. style属性中找到了什么。 You would require to use Window.getComputedStyle 您将需要使用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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM