How to make a calculator using JavaScript events?

前端 未结 1 1857
陌清茗
陌清茗 2020-12-20 10:01

I\'m trying to make a calculator in javascript, but I\'m having trouble understanding how to create variables that will store targeted DOM elements, input/outputs and how to

相关标签:
1条回答
  • 2020-12-20 10:05

    Well, I have remade your calculator in a simple but yet clear way, so you can now deal with each button press with one event handler that gives you the button that was pressed. now you have a good start point, happy coding :)

    document.querySelector(".buttons8").onclick = function(e) {
      if(e.target.nodeName === "BUTTON") {
        console.log(`${e.target.textContent} is pressed`);
        //do something
      }
    }
    * {
      box-sizing: border-box;
    }
    .calculator8 {
      width: 300px;
    }
    .buttons8 {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
    }
    .buttons8 button {
      width: 75px;
      height: 60px;
      font-size: 150%;
    }
    .screen8 {
      width: 100%;
      height: 80px;
      background-color: #333;
    }
    .b_blue {
      background-color: blue;
    }
    .b_red {
      background-color: red;
    }
    .b_yellow {
      background-color: yellow;
    }
    .b_green {
      background-color: green;
    }
    .b_lgray {
      background-color: #ffffd;
    }
    .b_vlgray {
      background-color: #eee;
    }
    .b_black {
      background-color: black;
    }
    .t_white {
      color: white;
    }
    <section class="calculator8">
      <h1>Calculator 8</h1>
      <input type="text" class="screen8" disabled>
      <div class="buttons8"> 
        <!-- operation buttons -->
        <button class="b_green">*</button>
        <button class="b_red">/</button>
        <button class="b_blue">-</button>
        <button class="b_yellow">+</button>
        <!-- number buttons -->
        <button class="b_lgray">.</button>
        <button class="b_lgray">9</button>
        <button class="b_lgray">8</button>
        <button class="b_lgray">7</button>
        <button class="b_lgray">6</button>
        <button class="b_lgray">5</button>
        <button class="b_lgray">4</button>
        <button class="b_lgray">3</button>
        <button class="b_lgray">2</button>
        <button class="b_lgray">1</button>
        <button class="b_lgray">0</button>
        <button class="b_lgray">=</button>
        <!-- other buttons -->
        <button class="b_vlgray">MR</button>
        <button class="b_vlgray">MC</button>
        <button class="b_vlgray">MS</button>
        <button class="b_black t_white">C</button>
      </div>
    </section>

    0 讨论(0)
提交回复
热议问题