简体   繁体   中英

Get image in JS from HTML src and replace it after CSS styling

How can i get the image or images from HTML and to replace in JS element.style.backgroundImage = "url('image')"? The example below work fine!

 var img = document.querySelector('.image-container'); img.style.backgroundImage = "url('https://images.unsplash.com/photo-1541443131876-44b03de101c5?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80"; img.style.backgroundRepeat = "no-repeat"; img.style.backgroundSize = "cover"; img.style.backgroundPosition = "center center"; img.src = img;
 .image-container { width: 425px; height: 575px; }
 <div class="image-container"> </div>

But i want to add img src and to get every image in JS

 var img = document.querySelector('.img').src; img.style.backgroundImage = "url('img')"; img.style.backgroundRepeat = "no-repeat"; img.style.backgroundSize = "cover"; img.style.backgroundPosition = "center center"; img.src = img;
 .image-container img { width: 425px; height: 575px; }
 <div class="image-container"> <img class="img"src="https://images.unsplash.com/photo-1541443131876-44b03de101c5?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80"> </div>

That it doesn't work, how can i fix it to work for every image in HTML to show with CSS properly changes like first example.

 // Select all images var images = document.querySelectorAll('.image-container img'); Array.from(images).forEach(img => { img.style.backgroundImage = "url('img')"; img.style.backgroundRepeat = "no-repeat"; img.style.backgroundSize = "cover"; img.style.backgroundPosition = "center center"; // Set url to whatever you want img.src = url; })

This code will loop through all images in image-containers and set the parent div to have the image src then remove the image from the dom.

I moved the repeating CSS background styles to the CSS class instead.

 var images = document.querySelectorAll('.image-container img'); images.forEach(function(img) { img.parentNode.style.backgroundImage = "url('" + img.src + "')"; img.remove(); })
 .image-container { height: 200px; width: 200px; background-repeat:no-repeat; background-Size:cover; background-position:center center; }
 <div class="image-container"><img src="https://images.unsplash.com/photo-1541443131876-44b03de101c5?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=1350&q=80"></div> <div class="image-container"><img src="https://via.placeholder.com/200/200/FF33AA"></div>

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