たとえば、計算されたスタイルを持つすべての要素を検索したいと思いますposition: fixed;
。CPUに大きな負荷をかけずにそれを行う方法は?
毎回繰り返してgetElementsByTagName('*')
からforループを実行するのが唯一の方法ですか?
たとえば、計算されたスタイルを持つすべての要素を検索したいと思いますposition: fixed;
。CPUに大きな負荷をかけずにそれを行う方法は?
毎回繰り返してgetElementsByTagName('*')
からforループを実行するのが唯一の方法ですか?
すべての ( *
) 要素を選択してgetComputedStyle
+を使用する代わりにgetPropertyValue
、次の手順に従うことができます。
すべての CSS ルールを ( [1]経由で) ループし、 を含むセレクターを取得します。document.styleSheets
position: fixed
style
属性が を含むすべての要素を選択しますposition: fixed
。
document.querySelectorAll
セレクターに一致するすべての要素を選択するために使用します。
window.getComputedStyle(elem, null).getPropertyValue('position')
等しいかどうかをテストします (より具体的なセレクターまたは によってオーバーライドされる可能性があります)。fixed
!important
この時点で、すべてのposition: fixed
要素を含む配列ができています。
[1]
外部スタイルシートは同じオリジン ポリシーのため、同じオリジンに配置する必要があります。
//[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
最善の策は DOM トラバーサルを使用することです。ほとんどのブラウザーでは並行して行われるため、ユーザーのコアを最大限に活用できるからです。