【问题标题】:How can I get random displayed images and background colours to match如何获得随机显示的图像和背景颜色以匹配
【发布时间】: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


【解决方案1】:

肯定有其他方法可以做到这一点(例如使用对象数组作为背景和颜色),但根据提供的代码,这里有一个简单的方法来组合这两个函数以使用相同的 randomIndex 值。

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 setRandomImageAndBackground() {
  const randomIndex = getRandomInt(imageSources.length);
   imageElement.src = imageSources[randomIndex];
  document.body.style.backgroundColor = backgroundColors[randomIndex];
}

setRandomImageAndBackground();

【讨论】:

  • 喔好吧。我明白你的意思了。为此非常感谢。非常感激
猜你喜欢
  • 2017-09-11
  • 1970-01-01
  • 2017-06-24
  • 2021-01-06
  • 2010-12-19
  • 2013-10-14
  • 2013-11-07
  • 2014-08-07
  • 2011-05-24
相关资源
最近更新 更多