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

标签 jquery css jquery-selectors

我想抓取页面上所有具有 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/

相关文章:

jQuery 下拉问题

javascript - jQuery 每个函数在同一元素中输出多个选择器

php - 隐藏页面加载上的提交按钮

html - 检测宽度与检测浏览器

css - Chrome/Safari无法填充Flex父级的100%高度

javascript - 如何在单个数据表列上启用 xeditable?

javascript - Jquery中如何通过索引获取子元素?

javascript - jquery 写一个 if

javascript - jQuery 数据表 - 如何使用 filter()?

javascript - jquery 中的元素定位