简体   繁体   English

为每次迭代添加颜色随机变化

[英]Add a random change in color for every iteration

I am writing a quiz sort of game and I want the background to change every time there is a new question. 我正在编写一个测验游戏,并且我希望每次遇到新问题时,背景都会改变。 Could someone help me with either how to code this or ideally the code? 有人可以帮助我如何编写此代码或理想情况下提供代码吗? (I haven't copied the array in as it links to a CSV. (我没有将数组复制到其中,因为它链接到CSV。

Here is my current code: 这是我当前的代码:

for (var i = 1; i <= 100; i++) {
    var number = Math.floor((Math.random() * 18) + 1);
    var stringGuess = prompt(questions[number])
    if (stringGuess == answers[number]) {
        alert("YOU GOT IT RIGHT!! THE ANSWER IS " + answers[number])
    } else if (stringGuess > answers[number]) {
        alert("Too high. The answer is " + answers[number]);
    } else {
        alert("Too low. The answer is " + answers[number]);
    }
}

Thank you!!! 谢谢!!!

For a random colour you could set a random RGB value using the function below. 对于随机颜色,您可以使用以下功能设置随机RGB值。 To set css background-color on an element you can use element.style.backgroundColour = colour; 要在元素上设置CSS背景颜色,可以使用element.style.backgroundColour = colour;。

function randomRGB(){
  return `rgb(${Math.floor(Math.random()*256)},${Math.floor(Math.random()*256)},${Math.floor(Math.random()*256)})`;
}
function setColour(element, colour){
  element.style.backgroundColour = colour;
}

Therefore, use this whenever you need to set a random background colour: setColour(document.getElementById("my-background-element"), randomRGB()); 因此,在需要设置随机背景色时,请使用此方法: setColour(document.getElementById("my-background-element"), randomRGB());

remembering to change "my-background-element" to the id of the background element you have. 记得将“ my-background-element”更改为您拥有的背景元素的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM