问题描述
有没有办法使用JavaScript来选择具有给定样式的所有元素?
Is there a way to select all elements that have a given style using JavaScript?
例如,我想在页面上所有绝对定位的元素。
Eg, I want all absolutely positioned elements on a page.
我假设在样式被明确声明的样式中更容易找到元素:
I would assume it is easier to find elements by style where the style is explicitly declared:
- 样式不是继承的(例如定位)
- 样式不是默认值(如position:static)。
我只限于这些规则吗?有没有更好的方法,当这些规则适用?
Am I limited to those rules? Is there a better method for when those rules apply?
我很乐意使用选择器引擎,如果这是由一个提供的(理想的Slick - Mootools 1.3)
I would happily to use a selector engine if this is provided by one (ideally Slick - Mootools 1.3)
编辑:
我想出了一个只能使用上述规则的解决方案。
它循环使用每个样式规则,然后页面上的选择器。
任何人都可以告诉我,如果这是更好的循环通过所有元素(如所有解决方案中建议)。
我知道在IE我必须将样式更改为小写,但是我可以使用cssText一次解析所有样式。
寻找最佳实践。
I came up with a solution that will only work with above rules.
It works by cycling through every style rule, and then selector on page.
Could anyone tell me if this is better that cycling through all elements (as recommended in all solutions).
I am aware that in IE I must change the style to lowercase, but that I could parse all styles at once using cssText. Left that out for simplicity.
Looking for best practice.
var classes = '';
Array.each(documents.stylesheets, function(sheet){
Array.each(sheet.rules || sheet.cssRules, function(rule){
if (rule.style.position == 'fixed') classes += rule.selectorText + ',';
});
});
var styleEls = $$(classes).combine($$('[style*=fixed]'));
推荐答案
Mootools:
var styleEls = $$('*').filter(function(item) {
return item.getStyle('position') == 'absolute';
});
这篇关于选择Element By CSS样式(所有具有给定样式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!