Как получить фоновое изображение элемента в html используя javascript - PullRequest
3 голосов
/ 29 января 2011

Я хочу получить фоновые изображения всех элементов HTML-страницы, которые установлены с помощью css или свойства фона элемента.

как я могу сделать это с помощью JavaScript?

Ответы [ 2 ]

5 голосов
/ 29 января 2011

Приведенная ниже функция 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 голосов
/ 29 января 2011

Вы могли бы нам jquery:

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