如何获取背景图像的 url

How to get the url of a background-image

我试图获取 url 背景图像以在 "userscript" 中使用它 但是如果不添加 class 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>

尝试像这样删除括号内的反引号:

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

ID 确保您从 DOM 中获取单个元素,而通过 class 获取您可以获得多个实例。

执行我将要向您展示的操作有点不好,但是鉴于只有一个 vjs-poster 实例 class 您可以通过 [=27 获取 vjs-poster 的所有实例=],select返回数组中的第一个实例,您可以在其中获取样式。

// 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>

Fiddle 这里:https://jsfiddle.net/r2bvdygs/