2011-01-29 47 views
2

我想获取所有使用css或元素背景属性设置的html页面元素背景图片。如何在html中使用javascript获取元素背景图片

我该如何使用javascript来做到这一点?

+0

获取当前有效的样式元素不同旧版本的IE和其他浏览器之间的很多 - 这是其中一个DOM框架真的可以为您节省很多麻烦的情况之一。 – Pointy 2011-01-29 15:41:49

+0

我如何使用dom框架来做到这一点? – 2011-01-29 15:44:43

回答

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]); 
5

你可以jQuery的我们:

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

但我认为,大多数情况下我们使用背景比背景图 – Sotiris 2011-01-29 15:52:04