【问题标题】:using forEach() to change background color after clicking a button单击按钮后使用 forEach() 更改背景颜色
【发布时间】:2021-09-05 00:32:42
【问题描述】:

我想在每次单击按钮时更改颜色。我使用 forEach 来检查每种颜色。但是在我单击一个按钮后,颜色变为“橙色”,即数组中的最后一种颜色。我的代码中是否缺少某些内容?

window.onload = function() {
    const btn = document.querySelector("button");
    btn.addEventListener("click", changeColor); 
}

function changeColor() {
    const colors = ["yellow","green","red","blue","orange"];
    colors.forEach(function(color) {
        document.body.style.backgroundColor = color;
    });
}
body{
    background-color:teal;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 180px;
}

button{
    background-color: white;
    font-size: 30px;
    width: 150px;
    height: 50px;
    border-style: solid;
    border-color: black;
    border-radius: 10px;
    cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/style.css">
    <script src="/js.js"></script>
    <title>1st project</title>
</head>
<body>
    <button class="button">Click me!</button>
    
</body>
</html>

【问题讨论】:

  • 每次点击时,它会将背景设置为数组中的每种颜色,依次以橙色结尾。
  • 所以在这种情况下我不能使用 forEach() 方法
  • 正确,你想要达到的效果。

标签: javascript foreach background-color


【解决方案1】:

如果你想按顺序改变颜色,这是一个简单的方法

let index = 0;

window.onload = function() {
    const btn = document.querySelector("button");
    btn.addEventListener("click", changeColor);
}

function changeColor() {
    const colors = ["yellow", "green", "red", "blue", "orange"];

    (index != colors.length - 1) ? index++ : index = 0; // Reset if index equals color array length

    document.body.style.backgroundColor = colors[index]
}

【讨论】:

    【解决方案2】:

    如果你想改变背景完全随机然后使用 Math.random() 方法(我设置最大值和最小值有点先进)

    RANDOM(更改为随机背景颜色)

           window.onload = function() {
          const btn = document.querySelector("button");
          btn.addEventListener("click", changeColor);
        }
        Math.randomNumber = (min, max)=> {
          return Math.round(Math.random() * (max - min) + min);
        };
        
        function changeColor() {
          const colors = ["yellow",
            "green",
            "red",
            "blue",
            "orange"];
    
          // Getting a random num b/w 0 and  colours array length 
          const num = Math.randomNumber(0, colors.length)
         // Chaining the colours 
          document.body.style.backgroundColor = colors[num];
        }
     
    

    LOOPING(如果你想在颜色数组中循环)

         window.onload = function() {
          const btn = document.querySelector("button");
          btn.addEventListener("click", changeColor);
        }
        // set Default color by changing the value 
        let currentNum = 0;
        function changeColor() {
          const colors = ["yellow",
            "green",
            "red",
            "blue",
            "orange"];
          
          if(currentNum >= colors.length - 1){
             currentNum = 0;
          }else{
            currentNum++
          }
          document.body.style.backgroundColor = colors[currentNum];
        }
    

    【讨论】:

      【解决方案3】:

      您必须以某种方式保存当前颜色,然后更改为下一个颜色。 为此,您可以将colors 数组的当前索引放在一个变量中:

      window.onload = function() {
          const btn = document.querySelector("button");
          btn.addEventListener("click", changeColor); 
      }
      
      let colorIndex = 0;
      const colors = ["teal", "yellow","green","red","blue","orange"];
      
      function changeColor() {
          colorIndex++;
          if ( colorIndex >= colors.length) {
              colorIndex = 0; // Circle back to the start
          }
          document.body.style.backgroundColor = colors[colorIndex];
      }
      body{
          background-color:teal;
          display: flex;
          justify-content: center;
          align-items: center;
          padding: 180px;
      }
      
      button{
          background-color: white;
          font-size: 30px;
          width: 150px;
          height: 50px;
          border-style: solid;
          border-color: black;
          border-radius: 10px;
          cursor: pointer;
      }
      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="width=device-width, initial-scale=1.0">
          <link rel="stylesheet" href="/style.css">
          <script src="/js.js"></script>
          <title>1st project</title>
      </head>
      <body>
          <button class="button">Click me!</button>
          
      </body>
      </html>

      【讨论】:

        【解决方案4】:

        每次单击时,您都将遍历 colors 数组,并将背景设置为数组中的每种颜色,以橙色结尾。

        相反,您需要跟踪最后一次点击的索引并在每次点击时递增,这里使用remainder operator(%) 循环回 0。

        let colorIndex=0;
        function changeColor() {
            const colors = ["yellow","green","red","blue","orange"];
            document.body.style.backgroundColor = colors[colorIndex];
            colorIndex = (colorIndex+1)%colors.length;
        }
        

        window.onload = function() {
            const btn = document.querySelector("button");
            btn.addEventListener("click", changeColor); 
        }
        
        let colorIndex=0;
        function changeColor() {
            const colors = ["yellow","green","red","blue","orange"];
            document.body.style.backgroundColor = colors[colorIndex];
            colorIndex = (colorIndex+1)%colors.length;
        }
        body{
            background-color:teal;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 180px;
        }
        
        button{
            background-color: white;
            font-size: 30px;
            width: 150px;
            height: 50px;
            border-style: solid;
            border-color: black;
            border-radius: 10px;
            cursor: pointer;
        }
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <link rel="stylesheet" href="/style.css">
            <script src="/js.js"></script>
            <title>1st project</title>
        </head>
        <body>
            <button class="button">Click me!</button>
            
        </body>
        </html>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-13
          • 2014-10-09
          • 2017-08-02
          • 1970-01-01
          • 2015-01-26
          • 2014-10-10
          • 1970-01-01
          相关资源
          最近更新 更多