<html> <head> <title>Calculator</title> <script language="javascript">... //数字验证 function ValidateIsNum(textbox) ...{ //如果为空,则默认为0 if(textbox.value == "") ...{ textbox.value = 0; return true; } //输入为非数字则清空并提示 if(isNaN(textbox.value)) ...{ textbox.value = ""; alert("请输入数字"); textbox.focus(); return false; } return true; } //改变提示 function ChangeTitle(radio) ...{ var title1 = document.getElementById("tdTitle1"); var title2 = document.getElementById("tdTitle2"); if(radio.id =="plus") ...{ title1.innerText = "请输入加数1:"; title2.innerText = "请输入加数2:" } if(radio.id == "minus") ...{ title1.innerText = "请输入被减数:"; title2.innerText = "请输入减数:" } if(radio.id == "multiply") ...{ title1.innerText = "请输入被乘数:"; title2.innerText = "请输入乘数:" } if(radio.id == "divide") ...{ title1.innerText = "请输入被除数:"; title2.innerText = "请输入除数:" } //有输入框为空,则Focus,不为空则计算 var text1 = document.getElementById("input1"); var text2 = document.getElementById("input2"); if(text1.value == "") text1.focus(); else if(text2.valuse == "") text2.focus(); else Calc(text1,text2); } function Calc(textbox1,textbox2) ...{ //验证输入是否合法 if(!ValidateIsNum(textbox1) || !ValidateIsNum(textbox2)) ...{ return; } var operand1 = parseFloat(textbox1.value); var operand2 = parseFloat(textbox2.value); var result = 0; if(document.getElementById("plus").checked == true) ...{ result = operand1 + operand2; } if(document.getElementById("minus").checked == true) ...{ result = operand1 - operand2; } if(document.getElementById("multiply").checked == true) ...{ result = operand1 * operand2; } if(document.getElementById("divide").checked == true) ...{ if(operand2 != 0) ...{ result = operand1 / operand2; } else ...{ alert("被除数不可为零"); textbox2.value = ""; textbox2.focus(); } } //输出 document.getElementById("inputResult").value = result; } //当focus时如果内容为0,则清空 function ClearWhenFocus(textbox) ...{ if(textbox.value == 0) ...{ textbox.value = ""; } } </script> </head> <body> <table border="2"> <tr> <td>请选择运算符:</td> <td> <input type="radio" checked="true" id="plus" name="operator" onclick="ChangeTitle(this)"></input>+ <input type="radio" id="minus" name="operator" onclick="ChangeTitle(this)"></input>- <input type="radio" id="multiply" name="operator" onclick="ChangeTitle(this)"></input>* <input type="radio" id="divide" name="operator" onclick="ChangeTitle(this)"></input>/ </td> </tr> <tr> <td id="tdTitle1">请输入加数1</td> <td><input type="text" id="input1" style="display:block" onkeyup="Calc(this,input2)" onfocus="ClearWhenFocus(this)"></input></td> </tr> <tr> <td id="tdTitle2">请输入加数2</td> <td><input type="text" id="input2" style="display:block" onkeyup="Calc(input1,this)" onfocus="ClearWhenFocus(this)"></input></td> </tr> <tr> <td>计算结果为:</td> <td><input type="text" id="inputResult" style="display:block"></input></td> </tr> </table> </body></html>