2011-01-29 3 views
2

CSSまたは要素のバックグラウンドプロパティを使用して設定されたすべてのhtmlページ要素の背景イメージを取得します。javascriptを使用してhtmlで要素の背景イメージを取得する方法

どうすればjavascriptを使用できますか?

+0

古いIEのバージョンや他のブラウザとの間にたくさん変わる - これはありますDOMフレームワークが実際に多くの問題を救うことができるケースの1つです。 – Pointy

+0

domフレームワークを使ってどうすればいいですか? –

答えて

4

getStyle()機能はhttp://www.quirksmode.org/dom/getstyles.html#link7(少し修正)から取られました。

もちろん、DOMの準備が整っていることを確認する必要があります。簡単な方法は、スクリプトをページの一番下、つまり閉じた</body>タグの内側に配置することです。

<script type="text/javascript"> 
    function getStyle(x, styleProp) { 
     if (x.currentStyle) var y = x.currentStyle[styleProp]; 
     else if (window.getComputedStyle) var y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp); 
     return y; 
    } 

     // Get all elements on the page 
    var elements = document.getElementsByTagName('*'); 

     // store the results 
    var results = [], 
     i = 0, 
     bgIm; 

     // iterate over the elements 
    for (;elements[i];i++) { 
      // get the background-image style property 
     bgIm = getStyle(elements[i], 'background-image'); 

      // if one was found, push it into the array 
     if (bgIm && bgIm !== 'none') { 
      results.push(bgIm); 
     } 
    } 

     // view the console to see the result 
    console.log(results); 
</script> 

画像自体のパスが必要なように聞こえました。

あなたは、実際の要素、変更たい場合は:に

results.push(bgIm); 

を:要素の現在有効なスタイルを取得

results.push(elements[i]); 
+0

はい画像へのパスが必要です –

+0

@ M.B.Asfoor:これはうまくいくと思います。試してみる。 IEの修正を加える必要があるかもしれません。 – user113716

5

あなたは可能性がjqueryの私たち:以下

imgs = []; 
$("*").each(function(i) { 
    if($(this).css("background-image") != "none") { 
    imgs.push($(this).css("background-image")); 
    } 
}); 
+0

しかし、私は、ほとんどの場合、背景画像よりも背景を使用すると思います – Sotiris

+0

その解決策は何ですか? –

+0

'css()'は計算されたスタイルを返すので 'background-image'が動作するはずです。 – RoToRa

関連する問題