也许网页中需要一个简单的计算器功能,这个时候就要掌握如何编写,起码应该会修改。
下面分享一个简单计算器效果。
代码实例如下:
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>web前端学习交流扣qun:731 771 211 志同道合者进</title>
<style type="text/css">
body{
font-size:12px;
color:#333;
}
ul input{
border:#ccc 1px solid;
border-right:#e2e2e2 1px solid;
border-bottom:#e2e2e2 1px solid;
height:15px;
line-height:15px;
padding:3px;
}
</style>
<script type="text/javascript">
function calculate(type,result,first,second){
var num=0;
firstValue=Number(first.value);
secondValue=Number(second.value);
if(firstValue==""||secondValue==""){
return false;
}
switch(type){
case 0:num=firstValue+secondValue;break;
case 1:num=firstValue-secondValue;break;
case 2:num=firstValue*secondValue;break;
case 3:num=firstValue/secondValue;break;
case 4:num=firstValue%secondValue;break;
}
result.value=num;
}
window.onload=function(){
var result=document.getElementById("result");
var reduce=document.getElementById("reduce");
var multiplication=document.getElementById("multiplication");
var division=document.getElementById("division");
var mod=document.getElementById("mod");
var first=document.getElementById("first");
var second=document.getElementById("second");
result.onfocus=function(){this.select()}
result.onclick=function(){calculate(0,result,first,second)}
reduce.onclick=function(){calculate(1,result,first,second)}
multiplication.onclick=function(){calculate(2,result,first,second)}
division.onclick=function(){calculate(3,result,first,second)}
mod.onclick=function(){calculate(4,result,first,second)}
}
</script>
</head>
<body>
<ul>
<li>第一个数:<input type="text" size="10" id="first"/></li>
<li>第二个数:<input type="text" size="10" id="second"/></li>
<li>计算结果:<input type="text" size="10" id="result" value="+" /></li>
</ul>
<input type="button" class="btn" value="–" id="reduce"/>
<input type="button" class="btn" value="×" id="multiplication"/>
<input type="button" class="btn" value="÷" id="division"/>
<input type="button" class="btn" value="%" id="mod"/>
</body>
</html>
网友评论