gpt4 book ai didi

javascript - 使用 Vanilla JS 在刷新时更改背景颜色

转载 作者:行者123 更新时间:2023-11-30 17:30:23 25 4
gpt4 key购买 nike

我在每次刷新时更改背景颜色时遇到一些问题。任何帮助表示赞赏。到目前为止,这是我的 js:

var colors = ['#760CE8', '#4782B1', '#E8890C'];

var changeBackground = function() {
document.body.style.background = colors([Math.floor(Math.random()*colors.length)]);
};

changeBackground();

最佳答案

你快到了。
在行中

document.body.style.background = colors([Math.floor(Math.random()*colors.length)]);

您需要删除 [Math.floor(Math.random()*colors.length)] 周围的括号。否则 JS 会认为你想调用 colors 作为函数。相反,您想按索引访问数组。这就是方括号的作用。所以改成

document.body.style.background = colors[Math.floor(Math.random()*colors.length)];

一切都会好起来的。

关于javascript - 使用 Vanilla JS 在刷新时更改背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23211006/

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