我想在单击按钮时更改应用程序的背景图像。我将图像放在一个数组中,然后随机选择背景图像。下面是代码。
const background = [
"image/2.png",
"image/4.png",
"image/9.png",
"image/14.png",
"image/12.png",
"image/17.png",
];
function changeColor() {
const getimage = `${
background[Math.floor(Math.random() * background.length)]
}`;
document.querySelector("body").style.backgroundImage = 'url("getimage")';
console.log(getimage);
}
控制台日志显示,在“单击按钮上”,getimage变量是随机变化的。但是在浏览器中,背景并没有改变!没有得到我想念的东西吗?
设置样式时,您将URL设置为getimage
作为字符串而不是元素。要解决您的问题,您只需要将其作为元素,要么为
document.querySelector("body").style.backgroundImage = `url("${getimage}")`;
// uses `` to include a variable using ${}
或:
document.querySelector("body").style.backgroundImage = 'url("' + getimage + '")'; // adds the variable in the middle of the string
尝试插入getimage
document.querySelector("body").style.background = `url(${getimage})`;