您能否解释一下,如何使用 javascript 或 jQuery 获取通过 css 添加的 html 元素样式的正确路径(例如 background:ulr()
)。
var img = document.querySelectorAll('*');
img.forEach(function(i){
var imageSrc = new Image();
i.addEventListener("mouseover", function(e){
if(i.style.background){
}
})
});
i.style.background
能找到正确的CSS DOM路径吗?
我添加了一个 fiddle 。
https://codepen.io/saifudazzlings/pen/VQvooy
最佳答案
HTMLElement.style
只会为您提供元素的内联样式的结果。如果需要获取从外部样式表计算出的样式,则需要使用Window.getComputedStyle
:
var bgImage = window.getComputedStyle(i).backgroundImage;
查看更新后的codepen here使用Window.getCompulatedStyle。当您将鼠标悬停在带有背景的 div
上时,将打印背景图像 URL。
关于javascript - 使用JavaScript获取CSS背景图像路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48577275/