3 回答
TA贡献1840条经验 获得超5个赞
使用 Object.keys() 方法获取颜色键,每次单击时,如果索引获得颜色大小,则递增索引,然后将索引设置为 0。请尝试此示例
document.addEventListener("click", changeBground);
let index = 0;
const colors = {
red: "#FF0000",
orange: "#FF7F00",
yellow: "FFFF00",
green: "#00FF00",
aqua: "#00FFFF",
blue: "#0000FF",
purple: "#8B00FF",
};
function changeBground() {
const keys = Object.keys(colors);
document.body.style.backgroundColor = colors[keys[index]];
if (index < keys.length) {
index += 1;
} else {
index = 0;
}
}
下面是一个示例
document.addEventListener("click", changeBground);
let index = 0;
const colors = {
red: "#FF0000",
orange: "#FF7F00",
yellow: "FFFF00",
green: "#00FF00",
aqua: "#00FFFF",
blue: "#0000FF",
purple: "#8B00FF",
};
function changeBground() {
const keys = Object.keys(colors);
document.body.style.backgroundColor = colors[keys[index]];
if (index < keys.length) {
index += 1;
} else {
index = 0;
}
}
TA贡献1815条经验 获得超6个赞
您可以使用 Math.random()
,生成一个随机数,允许您从对象中获取随机背景颜色与 Object.keys()相结合
,下面是一个工作片段:
document.addEventListener("click", changeBground);
var colors = {
red: "#FF0000",
orange: "#FF7F00",
yellow: "#FFFF00",
green: "#00FF00",
aqua: "#00FFFF",
blue: "#0000FF",
purple: "#8B00FF",
};
const colorKeys = Object.keys(colors);
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
function changeBground() {
const randKey = getRandomInt(0, colorKeys.length);
console.log(randKey, colorKeys[randKey] );
const color = colors[colorKeys[randKey]];
document.body.style.backgroundColor = color;
}
TA贡献1848条经验 获得超10个赞
您正在为颜色对象分配颜色,这就是为什么这不起作用的原因 - 使用belo代码这将起作用。
document.addEventListener("click", changeBground);
var counter = 0;
var colors = ['red', 'orange', 'yellow', 'green', 'aqua', 'blue', 'purple'];
function changeBground() {
document.body.style.background = colors[counter];
counter = counter < colors.length -1 ? counter + 1 : 0;
}
如果你想随机更新数组中的任何颜色,请使用下面的函数而不是上面的一个 -
function changeBground() {
var color = colors[Math.floor(Math.random() * colors.length)];
document.body.style.background = color;
}
添加回答
举报