首页 > 解决方案 > 从 HTML src 获取 JS 中的图像并在 CSS 样式后替换它

问题描述

如何从 HTML 中获取图像并在 JS element.style.backgroundImage = "url('image')" 中替换?下面的例子工作正常!

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>

但我想添加 img src 并在 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>

它不起作用,我该如何修复它以使 HTML 中的每个图像都能正确显示 CSS 更改,如第一个示例。

标签: javascript

解决方案


// 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;
})


推荐阅读