时间:2021-09-14 15:04:13 | 栏目:JavaScript代码 | 点击:次
本文实例为大家分享了JavaScript实现简单计算器功能的具体代码,供大家参考,具体内容如下
具体要求如下:
实现代码:
<html> <head> <meta charset="utf-8"> <title>计算器</title> <script> function myck(type){ var num1 = document.getElementById("num1"); var num2 = document.getElementById("num2"); if(type==1){ // 计算操作 var result = parseInt(num1.value) + parseInt(num2.value); alert(result); document.getElementById("resultDiv").innerText ="最终计算结果:"+ result; }else if(type==2){ var result = parseInt(num1.value) - parseInt(num2.value); alert(result); document.getElementById("resultDiv").innerText ="最终计算结果:"+ result; } else if(type==3){ var result = parseInt(num1.value) * parseInt(num2.value); alert(result); document.getElementById("resultDiv").innerText ="最终计算结果:"+ result; } else if(type==4){ if(confirm("是否正确清空?")){ // 清空 num1.value = ""; num2.value = ""; document.getElementById("resultDiv").innerText=""; } } } </script> </head> <body> <div style="margin-top: 100px;margin-left: 500px;"> <span style="font-size: 60px;">计算器</span> </div> <div> <div class="innerDiv" style="margin-left: 490px;"> 数 字1:<input id="num1" type="number" placeholder="请输入数字1"> </div> </div> <div> <div class="innerDiv" style="margin-left:490px;"> 数 字2:<input id="num2" type="number" placeholder="请输入数字2"> </div> </div> <div> <div style="margin-left: 500px;" class="innerDiv"> <input type="button" onclick="myck(1)" value="相 加"> <input type="button" onclick="myck(2)" value="相 减"> <input type="button" onclick="myck(3)" value="相 乘"> <input type="button" onclick="myck(4)" value="清 空"> </div> </div> <div id="resultDiv"> </div> </body> <style> .innerDiv{ margin-left: 420px; margin-top: 20px; } </style> </html>