使用CSS背景图像快速选择所有元素 [英] Quickly select all elements with css background image
问题描述
我想获取页面上具有css背景图像的所有元素.我可以通过过滤器功能来执行此操作,但是在包含许多元素的页面上它的速度非常慢:
$('*').filter(function(){return($(this).css('background-image')!=='');}).addClass('bg_found');
有没有更快的方法来选择带有背景图像的元素?
如果您知道任何标签都没有背景图片,则可以改进选择,以排除那些带有 http://jsfiddle.net/q63eU/ >
过滤器中的代码基于以下来源的getStyle代码: http://www.quirksmode.org/dom/getstyles.html
发布 for
语句版本,以避免在 .filter()
中调用函数.
var标签= document.getElementsByTagName('*'),埃尔;for(var i = 0,len = tags.length; i< len; i ++){el =标签[i];如果(el.currentStyle){if(el.currentStyle ['backgroundImage']!=='none')el.className + ='bg_found';}否则,如果(window.getComputedStyle){if(document.defaultView.getComputedStyle(el,null).getPropertyValue('background-image')!=='none')el.className + ='bg_found';}}
I want to grab all elements on a page that have a css background-image. I can do this via a filter function, but it's very slow on a page with many elements:
$('*').filter(function() {
return ( $(this).css('background-image') !== '' );
}).addClass('bg_found');
Is there any faster way to select elements with background images?
If there are any tags that you know will not have a background image, you can improve the selection be excluding those with the not-selector
(docs).
$('*:not(span,p)')
Aside from that, you could try using a more native API approach in the filter.
$('*').filter(function() {
if (this.currentStyle)
return this.currentStyle['backgroundImage'] !== 'none';
else if (window.getComputedStyle)
return document.defaultView.getComputedStyle(this,null)
.getPropertyValue('background-image') !== 'none';
}).addClass('bg_found');
Example: http://jsfiddle.net/q63eU/
The code in the filter is based on the getStyle code from: http://www.quirksmode.org/dom/getstyles.html
Posting a for
statement version to avoid the function calls in .filter()
.
var tags = document.getElementsByTagName('*'),
el;
for (var i = 0, len = tags.length; i < len; i++) {
el = tags[i];
if (el.currentStyle) {
if( el.currentStyle['backgroundImage'] !== 'none' )
el.className += ' bg_found';
}
else if (window.getComputedStyle) {
if( document.defaultView.getComputedStyle(el, null).getPropertyValue('background-image') !== 'none' )
el.className += ' bg_found';
}
}
这篇关于使用CSS背景图像快速选择所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!