【问题标题】:color changing background won't change color变色背景不会改变颜色
【发布时间】:2020-12-06 05:46:14
【问题描述】:

我正在为一个游戏编写代码,该代码需要使用 Math.floor()、Math.random() 和数组来创建随机十六进制代码的随机颜色闪烁背景。我希望背景每 1 秒改变一次颜色,但颜色甚至不会首先出现。这是我的代码;

<script>
var a = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
var b = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
var c = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
var d = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
var e = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
var f = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];

var A;
var B;
var C;
var D;
var E;
var F;

setInterval(function(){
A = a[Math.floor(Math.random()*a.length)];
B = b[Math.floor(Math.random()*b.length)];
C = c[Math.floor(Math.random()*c.length)];
D = d[Math.floor(Math.random()*d.length)];
E = e[Math.floor(Math.random()*e.length)];
F = f[Math.floor(Math.random()*f.length)];
},1000);

document.body.style.backgroundColor = "#"+A+B+C+D+E+F;
</script>

如果有人能帮忙,那就太好了!

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    这一行

    document.body.style.backgroundColor = "#"+A+B+C+D+E+F;
    

    应该进入你的setInterval

    setInterval(function() {
      A = a[Math.floor(Math.random()*a.length)];
      B = b[Math.floor(Math.random()*b.length)];
      C = c[Math.floor(Math.random()*c.length)];
      D = d[Math.floor(Math.random()*d.length)];
      E = e[Math.floor(Math.random()*e.length)];
      F = f[Math.floor(Math.random()*f.length)];
      document.body.style.backgroundColor = "#"+A+B+C+D+E+F;
    },1000);
    

    【讨论】:

      【解决方案2】:

      您可以在 setInterval 函数中访问变量 A、B、C、D、E、F,试试这个:

      var a = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
      var b = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
      var c = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
      var d = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
      var e = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
      var f = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];
      
      
      
      setInterval(function(){
          let A = a[Math.floor(Math.random()* a.length)];
          let B = b[Math.floor(Math.random()* b.length)];
          let C = c[Math.floor(Math.random()* c.length)];
          let D = d[Math.floor(Math.random()* d.length)];
          let E = e[Math.floor(Math.random()* e.length)];
          let F = f[Math.floor(Math.random()* f.length)];
          document.body.style.backgroundColor = '#' + A + B + C + D + E + F; 
      }, 1000);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-21
        • 2014-04-21
        • 2021-01-23
        • 2011-06-15
        • 1970-01-01
        • 2014-08-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多