简体   繁体   English

使用javascript获取存在某个CSS属性的所有元素?

[英]Get all elements with the presence of a certain CSS property using javascript?

Is there a way to get all elements on the DOM with the presence of a certain CSS property? 有没有办法让DOM上的所有元素都存在某个CSS属性? Say I wanted to get all elements with a background-image CSS value -- how could I select all of them? 假设我想要使用背景图像CSS值获取所有元素 - 我如何选择所有元素? I preferably want to avoid using Jquery. 我最好避免使用Jquery。

To be absolutely sure, you have get the style like this: 绝对肯定,你得到这样的风格:

var elms = document.all ? document.all : document.body.getElementsByTagName("*");
for (i = 0; i < elms.length; i++) {
    if ((elms[i].currentStyle && elms[i].currentStyle.backgroundImage.length > 0) ||
    (window.getComputedStyle &&
    window.getComputedStyle(elms[i]).getPropertyValue("background-image"))) {
        alert('found one!');
    } 
}​

CurrentStyle is for IE, getComputedStyle is for the rest. CurrentStyle用于IE,getComputedStyle用于其余部分。

on a modern browser you can use getComputedStyles 在现代浏览器上,您可以使用getComputedStyles

var elements = document.getElementsByTagName("*");
var haveBg = new Array();
for (i = 0; i < elements.length; i++) {
    var style = window.getComputedStyle(elements[i], null);
    if (style.getPropertyValue("background-image") != 'none') {
        haveBg.push(elements[i]);
    } 
}
var elms = document.all ? document.all : document.getElementsByTagName("*");
for (i = 0; i < elms.length; i++) {
   if (elms[i].style.backgroundImage.length > 0) {
        alert('found one!');
    } 
}

It would be better to use the exact tag name rather then '*' if you know what it would be before hand 最好使用确切的标签名称,而不是'*',如果你知道它之前会是什么

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

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