【问题标题】:Why doesn't the color change in my code dynamically each time I click the button?为什么每次单击按钮时代码中的颜色都不会动态变化?
【发布时间】:2022-10-05 00:42:48
【问题描述】:

每次单击该功能似乎只执行一次,然后我必须刷新页面并再次单击按钮以获得不同的背景颜色。对不起,如果这是一个愚蠢的问题,但我是一个初学者,任何帮助将不胜感激。

let bod = document.getElementById(\"bod\");
let random = Math.floor(Math.random() * 10);
let btn = document.getElementById(\"btn\");

btn.addEventListener(\"click\", function () {
  switch (random) {
    case 1:
      bod.style.backgroundColor = \"#FFFF00\";
      break;
    case 2:
      bod.style.backgroundColor = \"#000000\";
      break;

    case 3:
      bod.style.backgroundColor = \"#00FF00\";
      break;

    case 4:
      bod.style.backgroundColor = \"#0000FF\";
      break;

    case 5:
      bod.style.backgroundColor = \"#808080\";
      break;

    case 6:
      bod.style.backgroundColor = \"#A020F0.\";

      break;

    case 7:
      bod.style.backgroundColor = \"#FFC0CB\";
      break;

    case 8:
      bod.style.backgroundColor = \"#FF0000\";
      break;

    case 9:
      bod.style.backgroundColor = \"#FFFFFF\";
      break;

    case 10:
      bod.style.backgroundColor = \"#FFD700\";
      break;

    default:
    // code block
  }
});

    标签: javascript dom


    【解决方案1】:

    您在一开始只生成 1 次随机数,每次都需要生成它:

    let bod = document.getElementById("bod");
    let btn = document.getElementById("btn")
    
    btn.addEventListener("click", function(){
      let random = Math.floor(Math.random() * 10); // <-- HERE
      switch(random) {
        case 0: bod.style.backgroundColor = "#FFFF00"; break;
        case 1: bod.style.backgroundColor = "#000000"; break;
        case 2: bod.style.backgroundColor = "#00FF00"; break;
        case 3: bod.style.backgroundColor = "#0000FF"; break;
        case 4: bod.style.backgroundColor = "#808080"; break;
        case 5: bod.style.backgroundColor = "#A020F0"; break;
        case 6: bod.style.backgroundColor = "#FFC0CB"; break;
        case 7: bod.style.backgroundColor = "#FF0000"; break;
        case 8: bod.style.backgroundColor = "#FFFFFF"; break;
        case 9: bod.style.backgroundColor = "#FFD700"; break;
     }
    });
    <div id="bod">test</div>
    <button id="btn">button</button>

    更新:不要忘记 floor(random*10) 将生成从 0 到 9 的数字

    【讨论】:

    • 谢谢!这个答案很有见地。
    猜你喜欢
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-08
    • 2015-04-21
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    相关资源
    最近更新 更多