Я хочу добавить фоновое изображение в 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();
Добро пожаловать в StackOverflow.
В вашем массиве фотографий есть двойные кавычки, заключающие значение, вы должны удалить его.
Кавычки будут обработаны автоматически, вам просто нужно передать в div.style.background
обычную строку с нужным значением. В настоящее время вы передаете строку, начинающуюся с "
, что является недопустимым значением для этого атрибута, в результате чего оно не отображается в DOM.
Удалите двойной набор кавычек в массиве 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.info(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>
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"
];