简单的计算器制作
程序员文章站
2022-03-06 13:14:08
...
简单的计算器制作 ,输入数字验证,暂时只能做到用数据转换,如果输入的是数字后加字母还是无法排除,
如:parseInt(123asd) = 123
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.div1 {
width: 250px;
height: 400px;
background: #dbdbdb;
border: 1px solid slategray;
box-shadow: 0px 1px 3px 0px;
border-radius: 5px 5px;
margin: 30px 100px;
}
.d2 {
text-align: center;
}
.mt-4 {
margin-top: 10px;
padding: 10px;
}
</style>
</head>
<body>
<section class="div1 mt-4">
<div class="d2 mt-4"><span>计算器</span></div>
<input type="text" size="2" id="num1">
<select name="select" id="select">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
<option value="%">%</option>
</select>
<input type="text" size="2" id="num2">
<span>=</span>
<span id="res"></span><br>
<br>
<input type="button" value="计算" id="btn"> <button id="reBtn">重置</button>
<br>
<br>
<span id="outNum1"></span>
<br>
<span id="outNum2"></span>
</section>
</body>
<script>
document.getElementById('btn').onclick=function(){
document.getElementById('outNum1').innerHTML="";
document.getElementById('outNum2').innerHTML="";
document.getElementById('res').innerHTML="";
var num1 = parseInt(document.getElementById('num1').value);
var num2 = parseInt(document.getElementById('num2').value);
var maVa =document.getElementById('select').value;
if (isNaN(num1)) {
document.getElementById('outNum1').innerHTML ='第一个数据非数字,请重新输入!';
return;
}
if (isNaN(num2)) {
document.getElementById('outNum2').innerHTML ='第二个数据非数字,请重新输入!';
return;
}
switch (maVa){
case '+':
document.getElementById('res').innerHTML=num1+num2;
break
case '-':
document.getElementById('res').innerHTML =num1-num2;
break;
case '*':
document.getElementById('res').innerHTML = num1 * num2;
break
case '/':
if (num2==0){
document.getElementById('outNum2').innerHTML ='第二个数据不能为0,请重新输入!';
return;
}
document.getElementById('res').innerHTML = num1 / num2;
break;
case '%':
if (num2==0){
document.getElementById('outNum2').innerHTML ='第二个数据不能为0,请重新输入!';
return;
}
document.getElementById('res').innerHTML =num1%num2;
break;
}
};
document.getElementById('reBtn').onclick = function (){
document.getElementById('outNum1').innerHTML="";
document.getElementById('outNum2').innerHTML="";
document.getElementById('res').innerHTML="";
document.getElementById('num1').value="";
document.getElementById('num2').value="";
}
</script>
</html>
上一篇: PHP基金会为什么是个好事 ?
推荐阅读