首先是计算器的样式部分
<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字符串,并把它作为脚本代码来执行。 |