使用css背景图像快速选择所有元素

Jer*_*man 11 css jquery jquery-selectors

我想抓住页面上有css background-image的所有元素.我可以通过过滤功能来做到这一点,但在包含许多元素的页面上它非常慢:

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

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

use*_*716 19

如果您知道任何标签没有背景图像,您可以改进选择,不包括那些带有not-selector(docs)的标签.

$('*:not(span,p)')
Run Code Online (Sandbox Code Playgroud)

除此之外,您可以尝试在过滤器中使用更原生的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');
Run Code Online (Sandbox Code Playgroud)

示例: http ://jsfiddle.net/q63eU/

过滤器中的代码基于以下的getStyle代码: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';
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 你可以通过将`currentStyle` /`getComputedStyle`测试移出过滤函数来获得额外的(如果很小的话)性能提升:`$("*").filter(window.getComputedStyle?function(){return"none" === window.getComputedStyle(this,null).backgroundImage}:function(){return"none"=== this.currentStyle.backgroundImage}).addClass('bg_found');`(还有其他人**真的希望**我们可以创建多行评论吗?) (2认同)
  • @Jeremy:[试试这个.](http://jsfiddle.net/q63eU/2/)这是@Ben正在使用的概念,但有几个调整. (2认同)
  • ...最快将完全放弃`.filter()`并使用`for`循环.http://jsfiddle.net/q63eU/3/ (2认同)