【JavaScript】簡易的な計算機を作る方法。

JavaScript プログラミング

こんにちは、ダイキです。
今回は、JavaScript で、簡易的な計算機を作ってみたので、コードを載せておきます。

HTMLです。【JavaScript】簡易的な計算機を作る方法。


<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <title>JavaScript Test</title>
</head>
<body>
  <div class="body-flame">
    <div class="input-contents">
      <input type="text" id="num1">
      <input type="text" id="num2">
    </div>
    <div class="btn-contents">
      <button type="button" id="button-add">+</button>
      <button type="button" id="button-sub">-</button>
      <button type="button" id="button-mul">×</button>
      <button type="button" id="button-div">÷</button>
    </div>
    <div class="answer">
      <div id="box"></div>
    </div>
  </div>
  
  <script src="main.js"></script>
</body>
</html>

CSSです。【JavaScript】簡易的な計算機を作る方法。


body {
  margin-top: 10rem;
  text-align: center;
}
.body-flame {
  width: 500px;
  height: 300px;
  margin: 0 auto;
  background: #dedede;
}
.input-contents {
  margin-bottom: 1rem;
  padding-top: 5rem;
}
.btn-contents {
  margin-bottom: 1rem;
}
button {
  width: 50px;
  font-size: 30px;
}
#box {
  display: inline-block;
  width: 300px;
  background: #fff;
}

JavaScriptです。【JavaScript】簡易的な計算機を作る方法。


const buttonAdd = document.getElementById('button-add');
const buttonSub = document.getElementById('button-sub');
const buttonMul = document.getElementById('button-mul');
const buttonDiv = document.getElementById('button-div');

const num1 = document.getElementById('num1');
const num2 = document.getElementById('num2');

const box = document.getElementById('box');

buttonAdd.addEventListener('click', () => {
  const numberNum1 = Number.parseFloat(num1.value);
  const numberNum2 = Number.parseFloat(num2.value);
  const result = numberNum1 + numberNum2;
  
  box.textContent = result;
});
buttonSub.addEventListener('click', () => {
  const numberNum1 = Number.parseFloat(num1.value);
  const numberNum2 = Number.parseFloat(num2.value);
  const result = numberNum1 - numberNum2;
  
  box.textContent = result;
});
buttonMul.addEventListener('click', () => {
  const numberNum1 = Number.parseFloat(num1.value);
  const numberNum2 = Number.parseFloat(num2.value);
  const result = numberNum1 * numberNum2;
  
  box.textContent = result;
});
buttonDiv.addEventListener('click', () => {
  const numberNum1 = Number.parseFloat(num1.value);
  const numberNum2 = Number.parseFloat(num2.value);
  const result = numberNum1 / numberNum2;
  
  box.textContent = result;
});