2024-09-30 04:59:56
<!doctype html>
<html>
<head>
<title>计算器</title>
<meta charset="utf-8"/>
<style type="text/css">
.panel{
border:4px solid #ddd;
width:192px;
margin:100px auto;
}
.panel p,.panel input{
font-family:"微软雅黑";
font-size:20px;
margin:4px;
float:left;
}
.panel p{
width:122px;
height:26px;
border:1px solid #ddd;
padding:6px;
overflow:hidden;
}
.panel input{
width:40px;
height:40px;
border:1px solid #ddd;
}
</style>
<script type="text/javascript">
//参数e用来接收传入的event对象
function cal(e){
//1.获取事件源,处理button的事件
var obj=e.srcElement||e.target;
if(obj.nodeName !="INPUT"){
return;
}
var value=obj.value;
var p=document.getElementById("screen");
if(value=="C"){
//2.如果是[C],则清空p
p.innerText="";
}else if(value=="="){
//3.如果是[=],则运算
var exp=p.innerText;
try{
var result=eval("("+exp+")");
//如果正确执行,将结果写入p
p.innerText=result;
}catch(e){
//发生错误,给予错误提示
p.innerText="Error.";
}
}else{
//4.如果是其它按钮,则将value追加到p中
p.innerText+=value;
}
}
</script>
</head>
<body>
<!--在最外层的div上注册单击事件,传入event对象,然后在函数中通过event判断出事件来源于哪一个button,
进而做出应有的处理。这样的好处是,避免在button上大量的注册事件。-->
<div class="panel" onClick="cal(event);">
<div>
<p id="screen"></p>
<input type="button" value="C">
<div style="clear:both"></div>
</div>
<div>
<input type="button" value="7">
<input type="button" value="8">
<input type="button" value="9">
<input type="button" value="/">
<input type="button" value="4">
<input type="button" value="5">
<input type="button" value="6">
<input type="button" value="*">
<input type="button" value="1">
<input type="button" value="2">
<input type="button" value="3">
<input type="button" value="-">
<input type="button" value="0">
<input type="button" value=".">
<input type="button" value="=">
<input type="button" value="+">
<div style="clear:both"></div>
</div>
</body>
</html>
这是我自学时候写的计算器
2024-09-30 01:25:51
2024-09-30 07:15:39