整个计算器实现由html文件、js文件和css样式表三部分组成
整体效果:body里放俩div,一个大的包一个小的,小的放键盘,键盘div里放键盘。
html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>计算器</title> <link href="https://www.jb51.net/css/jsq_css.css"> </head> <body> <div> <input type="text" οnfοcus="this.blur();" value="0"> <div> <li οnclick="command(7);">7</li> <li οnclick="command(8);">8</li> <li οnclick="command(9);">9</li> <li οnclick="tools('https://www.jb51.net/','g')">÷</li> <li οnclick="command(4);">4</li> <li οnclick="command(5);">5</li> <li οnclick="command(6);">6</li> <li οnclick="tools('*','g')">×</li> <li οnclick="command(1);">1</li> <li οnclick="command(2);">2</li> <li οnclick="command(3);">3</li> <li οnclick="tools('-','g');">-</li> <li οnclick="command(0)";>0</li> <liοnclick="clearzero('j')">c</li> <liοnclick="equal('j');">=</li> <li οnclick="tools('+','g')";>+</li> </ul> </div> </div> </body> </html>
css:
*{margin: 0;padding: 0} li{list-style: none} .bor{margin: 0 auto;width: 400px;height: 520px;border: 2px solid #000; margin-top: 50px;overflow: hidden;text-align: center;} .s_text{margin: 0 auto;width: 330px;height: 80px;margin-top: 15px; border: 2px solid #000000;font-size: 30px;padding-left: 20px;} .main{margin: 0 auto;width: 350px;height: 400px;margin-top: 15px;} .main ul{display: flex;height: 100%;justify-content: space-between;flex-wrap: wrap;} .main ul li{width: 80px;height: 80px;border: 1px solid #000000; text-align: center; line-height:80px;font-size: 36px;cursor: pointer ;} .main ul li:hover{background: #eeeeee;}
js:(将这段代码写在body最下面)
<script type="text/javascript"> var resultDom = document.getElementById("result"); var operate = true; //操作符加锁 var afequ = true; //点击计算器执行函数(点数字的时候) function command(num){ //点击等号之后要进行一次清空 if(!afequ) { clearzero(); } //获取输入框中value的值 var str = resultDom.value;//在这里加一个判断, 如果第一位是0, 就用""填充 str = (str == "0" ? "":str);//条件操作符 str在判断无输入或者0的时候 都算作是0 str += num; //拼接数字, 然后赋值给文本框 resultDom.value = str;//.value获取文本框中的值 operate = true; //锁住操作符 } //四则运算 function tools(p,m){ if(operate){ var num = resultDom.value; num = (num == "0" ? "":num); resultDom.value = num + p; operate = false; } } //得出最后的结果 function equal(m){ var result = resultDom.value; var r = eval(result); //eval() 函数计算 JavaScript 字符串,并把它作为脚本代码来执行 resultDom.value =r; } //c归零的 function clearzero(){ resultDom.value=0; } </script>