简体   繁体   中英

Pass url value from background image style property

I have html code below:

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

Then how to set images/gallery-1.jpg to my imageURL variable javascript by querySelector? This is my try and error:

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

A little more code needed

You can change document.querySelector("[data-animate-effect]") to gallery[newIndex].querySelector("li") if preferred

 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); ">

Select the item, get the computed style , and retrieve the background image information. Then extract the URL from that data with a regular expression, and match .

 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'); ">

Use.replace() to regular expressions when possible, since it's often easier to read:

javascript code

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

Output:

images/gallery-1.jpg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM