9

たとえば、計算されたスタイルを持つすべての要素を検索したいと思いますposition: fixed;。CPUに大きな負荷をかけずにそれを行う方法は?

毎回繰り返してgetElementsByTagName('*')からforループを実行するのが唯一の方法ですか?

4

3 に答える 3

10

すべての ( *) 要素を選択してgetComputedStyle+を使用する代わりにgetPropertyValue、次の手順に従うことができます。

  • すべての CSS ルールを ( [1]経由で) ループし、 を含むセレクターを取得します。document.styleSheets position: fixed

  • style属性が を含むすべての要素を選択しますposition: 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
于 2012-01-07T11:24:08.183 に答える
0

最善の策は DOM トラバーサルを使用することです。ほとんどのブラウザーでは並行して行われるため、ユーザーのコアを最大限に活用できるからです。

于 2012-01-07T10:47:40.077 に答える