1.实现基本计算器功能,如图
2.逻辑代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>计算器</title> <!--设置样式--> <style> .showdiv{ text-align: center; margin:auto;/*设置居中*/ border: solid 1px; width: 400px; height: 500px; border-radius: 10px;/*设置边框角度*/ } input[type="text"]{ margin-top: 10px; width: 380px; height: 40px; font-size: 40px; } input[type="button"]{ margin: 10px; margin-top: 20px; width: 60px; height: 80px; font-size: 40px; font-weight: bold; } </style> <!--设置js代码--> <script type="text/javascript"> /*将按钮的值赋值给输入框*/ function num(btn){ //把不能为零去掉 if(document.getElementById("inp").value.match("除数")){ document.getElementById("inp").value = ""; } //获取button按钮的value var num = btn.value; console.log(num +" " +typeof(num)) //将值赋值给text文本框 switch(num){ case "c": document.getElementById("inp").value = ""; break; case "=": if(document.getElementById("inp").value.match("https://www.jb51.net/")){ if(document.getElementById("inp").value.split("https://www.jb51.net/")[1] == "0"){ document.getElementById("inp").value = "除数不能为零"; }else{ document.getElementById("inp").value = eval(document.getElementById("inp").value); } break; }else{ document.getElementById("inp").value = eval(document.getElementById("inp").value); break; } default: document.getElementById("inp").value = document.getElementById("inp").value+num; break; } } </script> </head> <body> <div class = "showdiv"> <input type="text" value="" readonly="readonly"/><br /> <input type="button" value="0"/> <input type="button" value="1"/> <input type="button" value="2"/> <input type="button" value="3"/><br /> <input type="button" value="4"/> <input type="button" value="5"/> <input type="button" value="6"/> <input type="button" value="7"/><br /> <input type="button" value="8"/> <input type="button" value="9"/> <input type="button" value="+"/> <input type="button" value="-"/><br /> <input type="button" value="*"/> <input type="button" value="https://www.jb51.net/"/> <input type="button" value="="/> <input type="button" value="c"/> </div> </body> </html>