【问题标题】:Quickly select all elements with css background image使用 css 背景图片快速选择所有元素
【发布时间】:2011-06-24 13:15:27
【问题描述】:

我想抓取页面上所有具有 CSS 背景图像的元素。我可以通过过滤器功能做到这一点,但在有很多元素的页面上它非常慢:

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

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

【问题讨论】:

  • 这段代码有效吗?但只是慢?

标签: jquery css jquery-selectors


【解决方案1】:

如果有任何您知道没有背景图像的标签,您可以改进选择,排除带有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';
    }
}

【讨论】:

  • +1 未记录的函数$.css 在这里可能有用,但我不知道与您建议的代码相比它的性能如何。
  • 您可以通过将currentStyle / getComputedStyle 测试移出过滤功能来获得额外的(如果很小的话)性能提升:$("*").filter(window.getComputedStyle ? function() { return "none" === window.getComputedStyle(this, null).backgroundImage } : function() { return "none" === this.currentStyle.backgroundImage }).addClass('bg_found');(其他人真的希望 我们可以创建多行 cmets?)
  • 这确实更快,主要是因为将背景图像样式与“无”而不是“”进行比较。在一个大页面上,我的时间从 14 多秒减少到大约 4 秒。
  • @Jeremy: Try this. 这是@Ben 使用的概念,但有一些调整。
  • ...最终最快的方法是完全放弃.filter() 并使用for 循环。 jsfiddle.net/q63eU/3
猜你喜欢
  • 2021-10-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 2014-07-31
  • 1970-01-01
相关资源
最近更新 更多