js简易计算器 基于JavaScript实现简易计算器
妄痴梦中 人气:0想了解基于JavaScript实现简易计算器的相关内容吗,妄痴梦中在本文为您仔细讲解js简易计算器的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:js,计算器,下面大家一起来学习吧。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算器</title> <style> .op { margin: 50px auto; width: 300px; height: 300px; border: 1px solid orange; background-color: lightskyblue; border-radius: 50px; } input { width: 210px; height: 30px; border-radius: 5px; } button { width: 30px; height: 30px; border-radius: 10px; } </style> </head> <body> <div class="op"> <h2 align="center">计算器</h2> <form name="calculator"> <table align="center"> <tr> <td>num1:</td> <td><input type="text" name="num1"></td> </tr> <tr> <td>num2:</td> <td><input type="text" name="num2"></td> </tr> <tr> <td colspan="2">          <button type="button">+</button>        <button type="button">-</button>        <button type="button">*</button>        <button type="button">/</button> </td> </tr> <tr> <td>结果:</td> <td><input type="text" name="result" disabled></td> </tr> </table> </form> </div> <script> //得到标签名下的所有元素对象,返回一个数组 let buttonArr = document.getElementsByTagName("button"); for (let but of buttonArr) { but.addEventListener('click', function () { let operator = this.innerHTML; count(operator); }); } function count(operator) { //得到form为calculator中name为num1的输入值 let num1 = parseFloat(document.calculator.num1.value); let num2 = parseFloat(document.calculator.num2.value); let result = ''; switch (operator) { case '+': result = num1 + num2; break; case '-': result = num1 - num2; break; case '*': result = num1 * num2; break; case '/': if (num2 == 0) { alert("除数不能为零"); return; } result = num1 / num2; break; } //将结果赋值于属性名name为result的input框 document.calculator.result.value = result; } </script> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
加载全部内容