gpt4 book ai didi

javascript - 不将数组中的图像添加到 div 背景

转载 作者:搜寻专家 更新时间:2023-10-31 22:52:38 25 4
gpt4 key购买 nike

我想从数组中将背景图像添加到 div。当我像这样设置背景时它会起作用:

div.style.background = "url(path/to/img.jpg) no-repeat"

但是如果我从这样的数组中取出它:

const array=[
'"url(path/to/img.jpg) no repeat"',
'"url(path/to/img2.jpg) no repeat"',
'"url(path/to/img3.jpg) no repeat"'
];
div.style.background = array[1];

它不起作用。

const grid = document.getElementById("grid");
const photos = ['"url(img/DSC_0387.JPG) no-repeat"', '"url(img/DSC_0389.JPG) no-repeat"', '"url(img/DSC_0392.JPG) no-repeat"', '"url(img/DSC_0393.JPG) no-repeat"', '"url(img/DSC_0399.JPG) no-repeat"'];

function add() {
let div = document.createElement('div');
div.style.background = photos[2];
div.style.borderRadius = "10px";
div.style.height = "350px";
div.style.backgroundSize = "contain";
grid.appendChild(div);
};
add();

最佳答案

删除 photos 数组中的双引号。

'"url(img/DSC_0387.JPG) no-repeat"' 变为 'url(img/DSC_0387.JPG) no-repeat'

const grid = document.getElementById("grid");
const photos = ['url(img/DSC_0387.JPG) no-repeat', 'url(img/DSC_0389.JPG) no-repeat','url(img/DSC_0392.JPG) no-repeat','url(img/DSC_0393.JPG) no-repeat','url(img/DSC_0399.JPG) no-repeat'];

function add(){
let div = document.createElement('div');
console.log(photos[2]);
div.style.background = photos[2];
div.style.borderRadius = "10px";
div.style.height = "350px";
div.style.backgroundSize = "contain";

grid.appendChild(div);
};
add();
<div id="grid"></div>

关于javascript - 不将数组中的图像添加到 div 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56370551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com