简体   繁体   English

用 vanilla js 替换背景图像 url 的一部分以获得一系列图像

[英]replace part of a background-image url with vanilla js for a series of images

I have a code that works well for changing a part of an src url of normal images我有一个代码可以很好地更改普通图像的 src url 的一部分

let svgz = document.querySelectorAll(".svg");
for (let i = 0; i < svgz.length; i++) {
  svgz[i].src = svgz[i].src.replace("light", "dark");
} 

I'd like to do the same with css background-image urls.我想对 css background-image url 做同样的事情。

I have created this snippet based on the above mentioned one but its not working:我根据上面提到的一个片段创建了这个片段,但它不起作用:

let svgbg = document.querySelectorAll(".svgbg");
for (let i = 0; i < svgbg.length; i++) {
    svgbg[i].style.backgroundImage = svgbg[i].style.backgroundImage.replace("light", "dark");
}

How can I change a background images url partially?如何部分更改背景图片网址?

actually it works, it was interfering with setting the default background-image url with a variable when the page loads.实际上它有效,它会在页面加载时干扰使用变量设置默认背景图像 url。 If the background images is a single image independent of theme it works like charm.如果背景图像是独立于主题的单个图像,它就像魅力一样。

This may be a case where the JS toggle method comes in useful, depending on exactly what is wanted of course.这可能是 JS 切换方法有用的情况,这当然取决于具体需要什么。 Code put up here in case of use to someone wanting to toggle between two background images (actually, between any two classes):如果有人想要在两个背景图像之间切换(实际上,在任何两个类之间),请在此处放置代码:

<style>
.svgbg {
  background-image: url(light.svg);/* replace with your light background url */
}
.svgbgdark {
  background-image:url(dark.svg);/* replace with your dark background url */
}
</style>
<div class="svgbg"></div>
<script>
let svgbg = document.querySelectorAll(".svgbg");
for (let i = 0; i < svgbg.length; i++) {
  svgbg.classList.toggle('svgbgdark');
}
</script>

Hi check the snippet below and let me know if this solves the problem.嗨,检查下面的代码片段,让我知道这是否解决了问题。

 let svgbg = document.querySelectorAll(".svgbg"); let bg = " url('img_tree.png')" console.log(bg); for (let i = 0; i < svgbg.length; i++) { //set your updated bg path here bg = " url('https://cdn.pixabay.com/photo/2020/08/19/00/13/sea-5499649__340.jpg')" console.log(bg); svgbg[i].style.backgroundImage = bg }
 .svgbg { background-size: 100% auto; width: 100%; height: 100%; z-index: -1; position: absolute; }
 <div class="svgbg"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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