javascript - 使用JavaScript获取CSS背景图像路径

标签 javascript

您能否解释一下,如何使用 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/

相关文章:

javascript - 模 % 大数 - 无穷大错误 - Javascript

javascript - 通过 JSON 进行搜索并在 HTML 页面中显示结果

输入后 JavaScript 更改输入颜色

javascript - Instafeed.js 和 jQuery colorbox

javascript - Apps 脚本 - 自动从 Google Drive 中删除超过 3 天的文件 - 获取文件列表

javascript - CSS3 在响应式设计中使用重叠或并排定位

javascript - JQuery 选择器不起作用

javascript - 在 Internet Explorer 中显示/隐藏选择选项组选项

javascript - 如何使用类型脚本在 angular2 中对格式进行编号?

javascript - 未调用 Amazon Alexa 技能回调