我想获取使用 css 或元素背景属性设置的所有 html 页面元素的背景图像。
我怎样才能使用javascript做到这一点?
The getStyle()
下面的函数取自http://www.quirksmode.org/dom/getstyles.html#link7 http://www.quirksmode.org/dom/getstyles.html#link7 (并稍作修改)。
当然,您需要确保 DOM 已准备就绪。一个简单的方法是将脚本放置在页面底部,就在结束语内</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>
听起来你想要图像本身的路径。
如果您想要实际的元素,请更改:
results.push(bgIm);
to:
results.push(elements[i]);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)