如何获取背景图像的网址



我试图获取背景图像的URL以在"Userscript"中使用它 但是如果不添加类 ID 就无法让它在此 HTML 代码上运行

<div class="vjs-poster" tabindex="-1" aria-disabled="false" style="background-image: url('https://www.example.com/image.png');"></div>

结果应该是 https://www.example.com/image.png

这是必需的结果,但希望在不按 ID 获取的情况下实现相同的结果:

// Get the image id, style and the url from it
var img = document.getElementById('vjs-poster'),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
// Display the url to the user
alert('Image URL: ' + bi);
<div class="vjs-poster" id="vjs-poster" tabindex="-1" aria-disabled="false" style="background-image: url(https://www.example.com);"></div>

ID 可确保从 DOM 获取单个元素,而按类获取可以获取多个实例。

做我将要向您展示的操作是一种糟糕的做法,但是鉴于只有一个 vjs-poster 类的实例,您可以通过 CLASS 获取 vjs-poster 的所有实例,并在返回的数组中选择第一个实例,您可以在其中获取样式。

// Get the image id, style and the url from it
var img = document.getElementsByClassName('vjs-poster'),
style = img.currentStyle || window.getComputedStyle(img[0], false),
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
// Display the url to the user
alert('Image URL: ' + bi);
<div class="vjs-poster" id="vjs-poster" tabindex="-1" aria-disabled="false" style="background-image: url(https://www.example.com);"></div>

在这里小提琴:https://jsfiddle.net/r2bvdygs/

尝试删除括号内的反引号,如下所示:

<div class="vjs-poster" tabindex="-1" aria-disabled="false" style="background-image: url(https://www.example.com/image.png);"></div>

最新更新