JS如何做一个简单的计算器!
代码:<<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
h1{
width: 30px;
height: 20px;
font-size: 20px;
border: 1px solid #0086b3;
text-align: center;
line-height: 20px;
}
div{
float: left;
}
ul{
display: none;
}
li{
font-size: 20px;
text-align: center;
line-height: 20px;
border: 1px solid #0086b3;
}
input{
float: left;
}
#but{
width: 30px;
height: 20px;
}
</style>
</head>
<body>
<input id="txt1" type="" >
<div id="div">
<h1 id="h1">+</h1>
<ul id="ul">
<li>+</li>
<li>-</li>
<li>*</li>
<li>/</li>
<li>%</li>
</ul>
</div>
<input id="txt2" type="" >
<input id="but" type="button" value="=">
</body>
<script>
var oT1=document.getElementById('txt1');
var oT2=document.getElementById('txt2');
var oBut=document.getElementById('but');
var oH=document.getElementById('h1');
var oUl=document.getElementById('ul');
var aLi=oUl.getElementsByTagName('li');
oH.onclick=function(){
oUl.style.display='block';
};
for(var i=0;i<aLi.length;i++) {
aLi[i].onclick = function () {
oUl.style.display = 'none';
oH.innerHTML = this.innerHTML;
}
};
oBut.onclick=function () {
var a=oH.innerHTML;
var n1=Number(oT1.value);
var n2=Number(oT2.value);
if (a=='+'){
alert(n1+n2);
} else if(a=='-'){
alert(n1-n2);
} else if(a=='*'){
alert(n1*n2);
} else if(a=='/'){
alert(n1/n2);
} else{
alert(n1%n2);
};
}
</script>
/html>
效果图:
如果想要更好看的可以自己调整一下哦!如果对你有帮助的话记着点个赞!有没看懂的就留个言,我看到了会回复你!