简体   繁体   English

不会将数组中的img添加到div背景中

[英]doesn't add img from array to div background

I want to add a background image to a div from an array. 我想将背景图像添加到数组的div中。 It works when I just set the background like this: 当我像这样设置背景时它可以工作:

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

But if I take it from an array such as this: 但是,如果我从这样的数组中取出它:

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];

it does not work. 这是行不通的。

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();

Remove the double set of quotes in the photos array. 删除photos数组中的双引号。

ie '"url(img/DSC_0387.JPG) no-repeat"' becomes 'url(img/DSC_0387.JPG) no-repeat' ie '"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> 

welcome to StackOverflow. 欢迎来到StackOverflow。

Your photos array has double-quotes wrapping the value, you should remove it. 你的照片数组有双引号包装值,你应该删除它。

The quotes will be handled automatically, you just need to pass a normal string to div.style.background with the desired value. 引号将自动处理,您只需要将正常的字符串传递给div.style.background并使用所需的值。 Currently you're passing a string that starts with " , thus being not a valid value for this attribute, resulting in this not being rendered on DOM. 目前,您传递的字符串以" ,因此不是此属性的有效值,因此不会在DOM上呈现”。

In photos Array change the values of the array as below. 在照片数组中,更改数组的值,如下所示。 Remove the single quotes for the values of the array. 删除数组值的单引号。

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"
];

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

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