【发布时间】:2023-01-05 20:59:11
【问题描述】:
我试图在每次访问页面时随机更改 4 种不同颜色之间的背景颜色,但我也希望页面上显示的图像与背景相匹配
例如,红色背景为 red.jpg,或蓝色背景为 blue.jpg
我遇到的问题是它们都是单独随机化的并且不匹配。
这就是我正在使用的
const imageElement = document.getElementById('random-image');
const imageSources = [ 'red.jpg', 'orange.jpg', 'yellow.jpg', 'green.jpg',];
const backgroundColors = [ 'red', 'orange', 'yellow', 'green',];
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function setRandomImage() {
const randomIndex = getRandomInt(imageSources.length);
imageElement.src = imageSources[randomIndex];
}
function setRandomBackgroundColor() {
const randomIndex = getRandomInt(backgroundColors.length);
document.body.style.backgroundColor = backgroundColors[randomIndex];
}
setRandomImage();
setRandomBackgroundColor();
【问题讨论】:
-
为什么不将函数组合起来,使它们都使用相同的索引呢?
-
你能解释一下吗,我对 javascript 还很陌生
-
仅生成一个随机索引和/或使用一个包含名称和颜色的对象数组。
标签: javascript html css