rsk*_*k82 6 javascript css dom computed-style
例如,我想找到所有已计算样式的元素position: fixed;.如何在不对CPU造成太大负担的情况下做到这一点?
是迭代每个getElementsByTagName('*')然后做循环唯一的方式?
您可以按照以下步骤操作*,而不是选择all()元素并使用getComputedStyle+ getPropertyValue.
document.styleSheets position: fixedstyle属性contains位置为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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2401 次 |
| 最近记录: |