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)
| 归档时间: |
|
| 查看次数: |
7620 次 |
| 最近记录: |