简易js计算器

本文介绍了一个简单的HTML计算器的设计与实现过程,包括使用表格布局计算器界面、CSS样式美化、以及JavaScript实现基本的数学运算功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先是计算器的样式部分

<table id="border">
<tr><td colspan="4"><input type="text" id="text1" value="0"/></td></tr>
<tr><td><input type="button" value="Power" /></td><td><input type="button" value="Clear" onclick="test3(this)" /></td><td><input type="button" value="Back" onclick="test4(this)" /></td><td><input type="button" value="占位"></td></tr>
<tr><td><input type="button" value="1" onclick="test(this)" id="1"/></td><td><input type="button" value="2" onclick="test(this)" /></td><td><input type="button" value="3" onclick="test(this)" /></td><td><input type="button" value="4" onclick="test(this)"/></td></tr>
<tr><td><input type="button" value="5" onclick="test(this)" /></td><td><input type="button" value="6" onclick="test(this)" /></td><td><input type="button" value="7" onclick="test(this)" /></td><td><input type="button" value="8" onclick="test(this)" /></td></tr>
<tr><td><input type="button" value="9" onclick="test(this)" /></td><td><input type="button" value="0" onclick="test(this)" /></td><td><input type="button" value="." onclick="test(this)" /></td><td><input type="button" value="=" onclick="test2(this)" /></td></tr>
<tr><td><input type="button" value="+" onclick="test(this)" id="+" /></td><td><input type="button" value="-" onclick="test(this)"/></td><td><input type="button" value="*" onclick="test(this)" /></td><td><input type="button" value="/" onclick="test(this)"/></td></tr>
</table>

</ TABLE>

 整体采用表来做的,onclick是js DOM中的响应事件.test(this)this指的就是输入标签这个对象

CSS:

<style>
#border{
    border:1px solid #0FC;
    width:300px;
    height:200px;
    cellspacing:0;
}
td{
    border:1px solid #CCC;
}
input{
    width:70px;
    height:30px;
}
#text1{
    width:300px;
}
</style>

JS部分


功能测试(事件){
    var text = document.getElementById('text1');
    text.value + = event.value;
}
function test2(){
        var text = document.getElementById('text1');
        text.value = eval(text.value); //使用eval函数处理计算JavaScript //字符串,并把它作为脚本代码来执行。
}
//清除功能
function test3(){
    var text = document.getElementById(“text1”);
    text.value = NULL;
}
function test4(){
//方法1个使用子串
    var text = document.getElementById('text1');
    var a = text.value;
    var a = a.substring(0,a.length-1);
    text.value = A;
    //方法2使用.split方法拆分字符串为数组,使用分裂方法切割,使用pop()方法,在使用加入拼接
}
</ SCRIPT>


 这其中最关键的是EVAL函数,

eval()
计算JavaScript字符串,并把它作为脚本代码来执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值