使用VanillaJS刷新时更改背景颜色

Change background color on refresh with Vanilla JS

本文关键字:背景 颜色 VanillaJS 刷新 使用      更新时间:2023-09-26

每次刷新时,我在更改背景颜色时遇到一些问题。感谢您的帮助。这是我迄今为止的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)]);

您需要删除CCD_ 1周围的括号。否则JS会认为您想将colors作为一个函数调用。相反,您希望通过索引访问数组。这就是方括号的作用。所以把它改成

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

一切都会好起来的。

您的代码很好,只需按照@TheShellfishMeme所说的操作,并将您的函数放入如下的body标记中:

<body onload="changeBackground();">

现在,每次刷新时,你都会得到不同的身体颜色。