快速选择所有带有css背景图片的元素

2024-04-14

我想抓取页面上具有 css 背景图像的所有元素。我可以通过过滤函数来做到这一点,但在包含许多元素的页面上速度非常慢:

$('*').filter(function() {
    return ( $(this).css('background-image') !== '' );
}).addClass('bg_found');

有没有更快的方法来选择带有背景图像的元素?


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) http://api.jquery.com/not-selector/.

$('*: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');

Example: http://jsfiddle.net/q63eU/ http://jsfiddle.net/q63eU/

过滤器中的代码基于以下位置的 getStyle 代码:http://www.quirksmode.org/dom/getstyles.html http://www.quirksmode.org/dom/getstyles.html


发布一个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';
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

快速选择所有带有css背景图片的元素 的相关文章

随机推荐