How to get the element background image in html using javascript

丶灬走出姿态 提交于 2020-01-02 07:22:11

问题


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

how can I do this using javascript?


回答1:


The getStyle() function below was taken from http://www.quirksmode.org/dom/getstyles.html#link7 (and slightly modified).

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

to:

results.push(elements[i]);



回答2:


You could us jquery:

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


来源:https://stackoverflow.com/questions/4837714/how-to-get-the-element-background-image-in-html-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!