使用JS编写简单的计算器
-
HTML写出计算器整体框架
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>计算器</title> <link rel="stylesheet" href="css/Calculator.css" /> </head> <body> <div id="calculator" class="calculator"> <div id="centent" class="centent"> <input id="cententShow" class="cententShow" type="text" value="0" /> <input class="cententButton1" type="button" value="7" onclick="getValue('7')" /> <input class="cententButton1" type="button" value="8" onclick="getValue('8')" /> <input class="cententButton1" type="button" value="9" onclick="getValue('9')" /> <input class="cententButton2" type="button" value="+" onclick="getValue('+')" /><br /> <input class="cententButton1" type="button" value="4" onclick="getValue('4')" /> <input class="cententButton1" type="button" value="5" onclick="getValue('5')" /> <input class="cententButton1" type="button" value="6" onclick="getValue('6')" /> <input class="cententButton2" type="button" value="-" onclick="getValue('-')" /><br /> <input class="cententButton1" type="button" value="1" onclick="getValue('1')" /> <input class="cententButton1" type="button" value="2" onclick="getValue('2')" /> <input class="cententButton1" type="button" value="3" onclick="getValue('3')" /> <input class="cententButton2" type="button" value="*" onclick="getValue('*')" /><br /> <input class="cententButton2" type="button" value="=" onclick="getValue('=')" /> <input class="cententButton1" type="button" value="0" onclick="getValue('0')" /> <input class="cententButton2" type="button" value="c" onclick="getValue('c')" /> <input class="cententButton2" type="button" value="/" onclick="getValue('/')" /><br /> </div> </div> <script type="text/javascript" src="js/Calculator.js"></script> </body> </html>
-
CSS对计算器进行美化(不影响内容的实现)
.calculator{ border: 2px lightgray solid; width: 304px; height: 380px; margin: auto; border-radius: 6px; } .centent{ border: 1px gray solid; width: 296px; height: 366px; margin: auto; margin-top: 5px; border-radius: 6px; } .cententShow{ width: 280px; height: 50px; font-size: 30px; margin-left: 4px; margin-top: 2px; border-radius: 6px; /*direction: rtl;*/ } .cententButton1,.cententButton2{ width: 60px; height: 60px; margin-left: 8px; margin-top: 8px; margin-bottom: 8px; font-size: 30px; border-radius: 6px; } .cententButton1{ background-color: orangered; }.cententButton2{ background-color: gray; }
-
JS实现计算器的运算功能
var str=""; function getValue(code){ var d=document.getElementById("cententShow"); str=d.value; if(code == "c"){ d.value="0"; }else if(code == "="){ d.value=eval(str); }else{ if(str == "0"){ str=""; } str=str+code; d.value=str; } }