2011-02-10 3 views
11

CSSの背景画像を持つページのすべての要素を取りたいと思います。私は、フィルタ機能を経由して、これを行うことができますが、それは多くの要素をページ上で非常に遅いです:CSSの背景画像ですべての要素をすばやく選択してください

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

は、背景画像を持つ要素を選択するための任意のより高速な方法はありますか?

+0

このコードは機能していますか?ただ遅い? – raidfive

答えて

18

背景画像がないことがわかっているタグがある場合は、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/

フィルタ内のコードは、からでgetStyleコードに基づいています:.filter()での関数呼び出しを避けるためにfor文のバージョンを投稿http://www.quirksmode.org/dom/getstyles.html


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

+1、素敵な答え。 – thirtydot

+1

+1文書化されていない関数 '$ .css'はここでは役に立つかもしれませんが、私はあなたの提案するコードと比較してどのような性能があるのか​​分かりません。 – lonesomeday

+2

フィルタ機能から 'currentStyle' /' getComputedStyle'テストを移動することで、パフォーマンスをさらに向上させることができます: '$(" * ")。filter(window.getComputedStyle?function {)" return "none "=== window.getComputedStyle(this、null).backgroundImage}:function(){return" none "=== this.currentStyle.backgroundImage})addClass( 'bg_found');'私たちは複数のコメントをつくることができますか?) –

関連する問題