欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Javascript 实现简单计算器实例代码

程序员文章站 2022-07-22 21:43:55
效果图: 刚开始做时没考虑到清零和退格两个功能,嘻嘻,后来加的整体与传统计算器比有点小瑕疵。 代码: <...

效果图:

Javascript 实现简单计算器实例代码

刚开始做时没考虑到清零和退格两个功能,嘻嘻,后来加的整体与传统计算器比有点小瑕疵。

代码:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>js简单计算器</title>

<style type="text/css">
*{
margin:0px;
padding:0px;
}
input{
margin-top:2px;
margin-left:2px;
width:230px;
height:30px;
text-align:right;
}
button{
margin-top:2px;
margin-left:2px;
width:50px;
height:50px;
}
#container{
margin-left:1px;
border:1px solid #e4e4e4;
background:#bbbbbb;
width:235px;
height:215px;
}
</style>

<script>

function onload(){
//加载完毕后光标自动对应到输入框
document.getelementbyid("input").focus();
}
//读取按钮的值,传给输入框
function inputevent(e){
//把val的值改为每个事件的innerhtml值
var val=e.innerhtml;
//获取input标签
var xsval=document.getelementbyid("input");
//标签里的value连接每个事件的innerhtml值
xsval.value+=val; 
}

//计算出结果
function inputoper(){
var xsval=document.getelementbyid("input");
xsval.value=eval(document.getelementbyid("input").value);
}
//清零
function clearnum(){
var xsval=document.getelementbyid("input");
xsval.value="";
document.getelementbyid("input").focus();
}
//退格
function backnum(){
var arr=document.getelementbyid("input");
arr.value=arr.value.substring(0,arr.value.length-1);
} 

</script>
</head>

<body onload="onload()">
<input id="input" type="text">
<div id="container">
<div>
<button onclick="inputevent(this)">1</button>
<button onclick="inputevent(this)">2</button>
<button onclick="inputevent(this)">3</button>
<button onclick="inputevent(this)">+</button>

</div>

<div>
<button onclick="inputevent(this)">4</button>
<button onclick="inputevent(this)">5</button>
<button onclick="inputevent(this)">6</button>
<button onclick="inputevent(this)">-</button>
</div>

<div>
<button onclick="inputevent(this)">7</button>
<button onclick="inputevent(this)">8</button>
<button onclick="inputevent(this)">9</button>
<button onclick="inputevent(this)">*</button>
</div>

<div>
<button onclick="inputevent(this)">0</button>
<button onclick="inputevent(this)">.</button>
<button onclick="inputoper(this)">=</button>
<button onclick="inputevent(this)">/</button>
</div>
</div>
<button onclick="clearnum()">清零</button>
<button onclick="backnum()">退格</button>
</body>

</html>

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!