[英]How to get the element background image in html using javascript
我想獲得使用css或元素背景屬性設置的所有html頁面元素的背景圖像。
我怎么能用javascript做到這一點?
你可以我們jquery:
imgs = [];
$("*").each(function(i) {
if($(this).css("background-image") != "none") {
imgs.push($(this).css("background-image"));
}
});
下面的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]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.