如何获取元素的背景图像在html使用javascript [英] How to get the element background image in html using javascript

查看:95
本文介绍了如何获取元素的背景图像在html使用javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to get all the html page elements' background images that are set using css or the element background property.

我如何使用javascript? / p>

how can I do this using javascript?

推荐答案

下面的 getStyle()函数来自 http://www.quirksmode.org/dom/getstyles.html#link7 (并稍作修改)。

当然,您需要确保DOM已准备就绪。一个简单的方法是将脚本放在页面底部,位于< / body> 标签内。

Of course you need to make sure the DOM is ready. An easy way to do that is to place the script toward the bottom of the page, just inside the closing </body> tag.

<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>

听起来像是你想要图片本身的路径。

It sounded like you want the path to the images themselves.

如果你想要实际的元素,改变:

If you wanted the actual elements, change:

results.push(bgIm);

到:

results.push(elements[i]);

这篇关于如何获取元素的背景图像在html使用javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆