欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简单计算器

程序员文章站 2022-03-03 22:37:07
...

<!DOCTYPE html>

<html lang="zh-CN">
<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" />
<title>Document</title>
</head>
<body>
<fieldset onload="init()">
<legend>小小计算器</legend>
<input type="number" name="n1" id="n1" value="0" oninput="calcu()" />
<select name="" id="opt" oninput="calcu()">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="number" name="n2" id="n2" value="0" oninput="calcu()" />
<span>=</span>
<span class="res">0</span>
</fieldset>
<script>
const n1 = document.querySelector(“#n1”);
const n2 = document.querySelector(“#n2”);
const opt = document.querySelector(“#opt”);

  1. function init() {
  2. n1.value = 0;
  3. n2.value = 0;
  4. opt.value = "+";
  5. }
  6. function calcu() {
  7. let value1 = n1.value * 1;
  8. let value2 = n2.value * 1;
  9. let optType = opt.value;
  10. let res = 0;
  11. switch (optType) {
  12. case "+":
  13. res = value1 + value2;
  14. break;
  15. case "-":
  16. res = value1 - value2;
  17. break;
  18. case "*":
  19. res = value1 * value2;
  20. break;
  21. case "/":
  22. if (value2 === 0) throw "除数不能为零";
  23. res = (value1 / value2).toFixed(2);
  24. break;
  25. default:
  26. throw "非法操作";
  27. }
  28. document.querySelector(".res").textContent = res;
  29. }
  30. </script>

</body>
</html>
简单计算器