javascript - 从 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 更改,如第一个示例。
解决方案
// 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;
})
推荐阅读
- c# - 我可以在我的代码中使用我的标头上发送的 JWT 令牌吗?
- html - 图标未正确加载
- c# - 每次光标在它上面时,我如何统一创建我的游戏对象的亮点?
- azure-resource-manager - ARM模板中是否可以有条件属性
- r - 如何使用 rmarkdown::render() 在 html 中呈现 gganimate 图,而不产生不需要的输出
- php - 如何将 REQUEST_URI 从 htaccess 传递给 PHP
- xml - alpakka-xml 可以处理多个xml文件吗?
- generics - 与方法引用配对的泛型类型
- javascript - 如何正确实现 videojs-dvrseekbar 插件?
- caching - CachePut 跳过必填字段