从背景图像样式属性传递url值



我的html代码如下:

<li class="name1 name2 name3" data-animate-effect="fadeIn" style="background-image: url(images/gallery-1.jpg); ">

那么如何通过querySelector将images/gallery-1.jpg设置为我的imageURL变量javascript ?这是我的尝试和错误:

let imageURL = gallery[newIndex].querySelector("li").style.background.url;

需要更多代码

如果您愿意,可以将document.querySelector("[data-animate-effect]")更改为gallery[newIndex].querySelector("li")

console.log(document.querySelector("[data-animate-effect]")
.style.backgroundImage.match(/"(.*)"/)[1])
<li class="name1 name2 name3" data-animate-effect="fadeIn" style="background-image: url(images/gallery-1.jpg); ">

选择项目,获取计算样式,并检索背景图像信息。然后使用正则表达式和match从该数据中提取URL。

const li = document.querySelector('li');
const style = window.getComputedStyle(li);
const imageUrl = style.getPropertyValue('background-image');
console.log(imageUrl.match(/"(.+)"/)[1]);
<li class="name1 name2 name3" data-animate-effect="fadeIn" style="background-image: url('https://dummyimage.com/100x100/666/ff0'); ">

尽可能使用.replace()来替换正则表达式,因为它通常更容易阅读:

javascript代码

var image = $("li").css("background-image")
image = image.replace(/.*s?url(['"]?/, '').replace(/['"]?).*/, '')

输出:

images/gallery-1.jpg

相关内容