如何查询整个DOM匹配某些计算样式的元素?(纯粹的js)

rsk*_*k82 6 javascript css dom computed-style

例如,我想找到所有已计算样式的元素position: fixed;.如何在不对CPU造成太大负担的情况下做到这一点?

是迭代每个getElementsByTagName('*')然后做循环唯一的方式?

Rob*_*b W 8

您可以按照以下步骤操作*,而不是选择all()元素并使用getComputedStyle+ getPropertyValue.

  • 遍历所有CSS规则(通过[1])并获取包含的选择器.document.styleSheets position: fixed
  • 选择style属性contains位置为fixed`的所有元素.
  • 使用document.querySelectorAll来选择匹配选择其中的所有元素.

    • 测试是否window.getComputedStyle(elem, null).getPropertyValue('position')等于fixed过滤不在固定位置的元素(可能通过更具体的选择器覆盖,或者!important).
    • 如果匹配,则按元素中的元素
  • 此时,您有一个包含所有position: fixed元素的数组.

[1] 由于相同的原始策略,外部样式表必须位于相同的原点.

代码(小演示:http://jsfiddle.net/GtXpw/):

//[style*=..] = attribute selector
var possibilities = ['[style*="position:fixed"],[style*="position: fixed"]'],
    searchFor = /\bposition:\s*fixed;/,
    cssProp = 'position',
    cssValue = 'fixed',
    styles = document.styleSheets,
    i, j, l, rules, rule, elem, res = [];

for (i=0; i<styles.length; i++) {
    rules = styles[i].cssRules;
    l = rules.length;
    for (j=0; j<l; j++) {
        rule = rules[j];
        if (searchFor.test(rule.cssText)) {
            possibilities.push(rule.selectorText);
        }
    }
}
possibilities = possibilities.join(',');
possibilities = document.querySelectorAll(possibilities);
l = possibilities.length;
for (i=0; i<l; i++) {
   elem = possibilities[i];
   // Test whether the element is really position:fixed
   if (window.getComputedStyle(elem, null).getPropertyValue(cssProp) === cssValue) {
       res.push(elem);
   }
}
res; //<-- = Array containing all position:fixed elements
Run Code Online (Sandbox Code Playgroud)