发布时间:2025-12-09 13:50:05 浏览次数:4
注:本人为初学者,欢迎各位大神指教
在线试一试
简单计算器实现效果:
HTML代码counter.html
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>计算器</title><link rel="stylesheet" type="text/css" href="css/counter.css" /><script type="text/javascript" src="js/counter.js"></script></head><body><p ><p ><form><input type="text" value="" /></form></p><p ><form><input type="button" value="清屏" onclick="cl(this.value)" /><input type="button" value="退格" onclick="cl(this.value)"/><p ><input type="button" value="÷" onclick="eva(this.value)"/><input type="button" value="×" onclick="eva(this.value)"/><input type="button" value="-" onclick="eva(this.value)"/><input type="button" value="+" onclick="eva(this.value)"/><input type="button" value="=" onclick="eva(this.value)"/></p><p ><input type="button" value="7" onclick="show(this.value)"/><input type="button" value="8" onclick="show(this.value)"/><input type="button" value="9" onclick="show(this.value)"/><input type="button" value="4" onclick="show(this.value)" /><input type="button" value="5" onclick="show(this.value)" /><input type="button" value="6" onclick="show(this.value)"/><input type="button" value="1" onclick="show(this.value)"/><input type="button" value="2" onclick="show(this.value)"/><input type="button" value="3" onclick="show(this.value)"/><input type="button" value="0" onclick="show(this.value)"/><input type="button" value="." onclick="show(this.value)"/><input type="button" value="+/-" onclick="eva(this.value)"/></p></form></p></p></body></html>CSS代码counter.css
.counter{background-color: #E0E0E0;width: 440px;height: 460px;padding: 20px;}.counter .counter_top{width: 440px;height: 53px;background-color: #fff;}.counter .counter_top input{width: 440px;height: 53px;border: 0px;}.counter_down .CE{width: 152.5px;height: 45px;margin: 15px 15px 0px 0px;}.counter_down .cou{width: 95px;height: 45px;margin-bottom: 15px;}.down_right{width: 95px;float: right;margin-top: 15px;}.counter_down .num{width: 95px;height: 45px;margin: 15px 16px 0px 0px;}js代码counter.js
var a=0;var b;var c = 0;function show(value) {document.getElementById("top").value +=value;}function eva(value){c=parseFloat(document.getElementById("top").value);if (value=="=") {if(b=="+"){document.getElementById("top").value=(a+c);}else if(b=="-"){document.getElementById("top").value=(a-c);}else if(b=="×"){document.getElementById("top").value=(a*c);}else if(b=="÷"){if(c==0){document.getElementById("top").value="分母不能为0";}else{document.getElementById("top").value=(a/c);}}}else{a=parseFloat(document.getElementById("top").value);document.getElementById("top").value="";b=value;if(b=="+/-"){a=-a;document.getElementById("top").value=a;}}}function cl(value){if(value=="清屏"){document.getElementById("top").value="";}else{document.getElementById("top").value=document.getElementById("top").value.substring(0,(document.getElementById("top").value.length-1))}}