Mil*_*los 1 html javascript css
我正在使用CSS选择器来匹配某些元素,我想用javascript检测这些元素.我发现我可以在这些元素的css中设置颜色,然后通过颜色检索它们.问题是style.backgroundColor仅返回if inline样式.
这是我的尝试 http://jsfiddle.net/qUDjb/29/
CSS
div{background-color: lightgrey;}
Run Code Online (Sandbox Code Playgroud)
JS
alert(document.getElementById("myDiv").style.backgroundColor);
Run Code Online (Sandbox Code Playgroud)
有没有办法让颜色检测工作,或者有人可以更好地了解如何检测受影响的元素(通过css选择器)?
我不想为此使用jquery.
element.style只返回内联样式声明(或JS中添加的声明elements.style['foo'] = "bar".它并不总是浏览器应用的规则,例如CSS声明!important可以覆盖内联样式.你也可以有多个CSS声明相互覆盖和浏览器使用CSS选择器优先级规则决定应用哪一个.
要获得实际应用的规则,您应该使用getComputedStyle方法:http://jsfiddle.net/qUDjb/31/
window.getComputedStyle(document.getElementById("myDiv"))['background-color']
Run Code Online (Sandbox Code Playgroud)
getComputedStyle上的MDN
编辑:如果你想通过背景颜色获取元素它不是真正的最佳方式,但它可以获得元素的集合,然后按计算的样式值过滤:http://jsfiddle.net/qUDjb/36 /
CSS
p:nth-child(2n) {
background-color:lightgrey;
}
Run Code Online (Sandbox Code Playgroud)
JS
var getElementsByBackgroundColor = function( collection, color ){
// convert the color string to the format used by browser
var div = document.createElement('div');
div.style.backgroundColor = color;
var computedColor = div.style.backgroundColor;
// compare computed background color and return matching elements
return [].slice.call( collection ).filter( function( item ){
return window.getComputedStyle( item )['background-color'] == computedColor;
});
}
console.log( getElementsByBackgroundColor( document.querySelectorAll('p'), 'lightgrey') );
Run Code Online (Sandbox Code Playgroud)