日期:2014-05-17  浏览次数:20587 次

简单的网页计算器(JS、HTML)
最近才学JS,做了个简单的网页计算器,除了js部分属性的使用,还接触了下能触发键盘的event事件,呵呵,觉得挺有意义的。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> 计算器 </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
<SCRIPT LANGUAGE="JavaScript">
<!--
	var result = "";
	var view  ;
	var count = 1;
	var equal;
	
	function addNum(num){
		view = document.getElementById("view");		
		equal = document.getElementById("equal");

		if(count % 2 == 0){
			result = "";
			view.setAttribute("value","0");
			count = 1;
		} 
		
		result = result+""+num;
		
		view.setAttribute("value",result);

		equal.focus();
	}

	function getResult(){
		if(view!=null){
			result = result+" = "+eval(result);
			view.setAttribute("value",result);
			count++;
		}
		
	}
 
	//触发键盘上的enter键,在火狐浏览器下不能触发键盘按钮,遗憾。
	function onkeypress()
	{
		if ( event.keyCode=='13' )
		{
			getResult();
		}
	}
//-->
</SCRIPT>
 

 <style>
	input {
		height:30px;
		width:60px;
	}
 </style>
 </HEAD>

 <BODY>
	<table align="center" width="30%" style="border-left:2px solid #000;border-top:2px solid #000;border-right:2px solid #000;border-bottom:2px solid #000;">
		<tr>
			<td colspan="6" bgcolor="#000099" height="30px" align="center">
				<font color="#ffffff"><b>计算器</b></font>
			</td> 
		<tr>
		<tr>
			<td colspan="4">
				<input id="view" size="60" style="width:460px;text-align:right;" value="0"/>
			</td>
			<td >
				<input id="equal" type="button" value="=" onclick="getResult();"/>
			</td>
		<tr>
		<tr>
			<td>
				<input id="1" type="button" value="1" onclick="addNum(1);"/>
			</td>
			<td>
				<input id="2" type="button" value="2" onclick="addNum(2);"/>
			</td>
			<td>
				<input id="3" type="button" value="3" onclick="addNum(3);"/>
			</td>
			<td>
				<input id="4" type="button" value="4" onclick="addNum(4);"/>
			</td>
			<td>
				<input id="+" type="button" value="+" onclick="addNum('+');"/>
			</td>
		<tr><tr>
			<td>
				<input id="5" type="button" value="5" onclick="addNum(5);"/>
			</td> 
			<td>
				<input id="6" type="button" value="6" onclick="addNum(6);"/>
			</td>
			<td>
				<input id="7" type="button" value="7" onclick="addNum(7);"/>
			</td>
			<td>
				<input id="8" type="button" value="8" onclick="addNum(8);"/>
			</td>
			<td>
				<input id="-" type="button" value="-" onclick="addNum('-');"/>
			</td>
		<tr><tr> 
			<td>
				<input id="9" type="button" value="9" onclick="addNum(9);"/>
			</td>
			<td>
				<input id="0" type="button" value="0" onclick="addNum(0);"/>
			</td>
			<td>
				<input id="dot" type="button" value="." onclick="addNum('.');"/>
			</td>
			<td>
				<input id="/" type="button" value="/" onclick="addNum('/');"/>
			</td>
			<td>
				<input id="*" type="button" value="*" onclick="addNum('*');"/>
			</td>
		<tr> 
	</table>
 </BODY>
</HTML>