我想抓取页面上所有具有 css 背景图像的元素。我可以通过过滤功能来做到这一点,但它在包含许多元素的页面上非常慢:
$('*').filter(function() {
return ( $(this).css('background-image') !== '' );
}).addClass('bg_found');
有没有更快的方法来选择带有背景图片的元素?
最佳答案
如果您知道有任何标签不会有背景图片,您可以改进选择,将带有 not-selector
(docs) 的标签排除在外.
$('*:not(span,p)')
除此之外,您可以尝试在过滤器中使用更原生的 API 方法。
$('*').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');
示例: http://jsfiddle.net/q63eU/
过滤器中的代码基于来自:http://www.quirksmode.org/dom/getstyles.html 的 getStyle 代码
发布 for
语句版本以避免 .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';
}
}
关于jquery - 快速选择带有css背景图片的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4952337/