如何使用javascript在html中获取元素背景图像

Muh*_*our 3 html javascript css background-image

我想获得使用css或元素背景属性设置的所有html页面元素的背景图像.

我怎么能用javascript做到这一点?

ste*_*tef 5

你可以我们jquery:

imgs = [];
$("*").each(function(i) { 
  if($(this).css("background-image") != "none") { 
    imgs.push($(this).css("background-image")); 
  } 
});
Run Code Online (Sandbox Code Playgroud)


use*_*716 5

以下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>
Run Code Online (Sandbox Code Playgroud)

这听起来像你想要自己的图像路径.

如果您想要实际元素,请更改:

results.push(bgIm);
Run Code Online (Sandbox Code Playgroud)

至:

results.push(elements[i]);
Run Code Online (Sandbox Code Playgroud)