[英]Set a background image for a button in html and then change the images from javascript
[英]Background image change from array of images on button click in JavaScript
我想在单击按钮时更改我的应用程序的背景图像。 我将图像放在一个数组中并随机选择背景图像。 下面是代码。
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})`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.