DIV CSS 佈局教程網

用 JS 打造網頁版計算機的簡易實作
編輯:關於JavaScript     

以下示範如何用 JavaScript 做出一個網頁版的簡單計算機:

複製程式碼 程式碼如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>計算器</title>
<script language="javascript" type="text/javascript">
 var clearFlag=false;
 function getNum(num){
 var objresult=document.getElementById("result");
 if(clearFlag){
 objresult.value="";
 clearFlag=false;
 }
 objresult.value+=num;
 }
function getResult(){
 var objresult=document.getElementById("result");
 objresult.value=objresult.value+"="+eval(objresult.value);
 clearFlag=true;
}
</script>
</head>
<body>
<table width="200" border="1" cellpadding="2">
  <tr>
    <td colspan="4"><input type="text" name="result" id="result" size="33"></td>
  </tr>
  <tr>
    <td width="56"><input type="button" value="  1   " onclick="getNum(1)"></td>
    <td width="56"><input type="button" value="  2   " onclick="getNum(2)"></td>
    <td width="51"><input type="button" value="  3   " onclick="getNum(3)"></td>
    <td width="58"><input type="button" value="  +   " onclick="getNum('+')"></td>
  </tr>
  <tr>
    <td><input type="button" value="  4   " onclick="getNum(4)"></td>
    <td><input type="button" value="  5   " onclick="getNum(5)"></td>
    <td><input type="button" value="  6   " onclick="getNum(6)"></td>
    <td><input type="button" value="  -   " onclick="getNum('-')"></td>
  </tr>
  <tr>
    <td><input type="button" value="  7   " onclick="getNum(7)"></td>
    <td><input type="button" value="  8   " onclick="getNum(8)"></td>
    <td><input type="button" value="  9   " onclick="getNum(9)"></td>
    <td><input type="button" value="  *   " onclick="getNum('*')"></td>
  </tr>
  <tr>
    <td><input type="button" value="  0   " onclick="getNum(0)"></td>
    <td><input type="button" value="  .   " onclick="getNum('.')"></td>
    <td><input type="button" value="  =   " onclick="getResult()"></td>
    <td><input type="button" value="  /   " onclick="getNum('/')"></td>
  </tr>
</table>
</body>
</html>

核心邏輯很精簡:getNum 負責把按下的數字或運算符累加到輸入框(並用 clearFlag 控制計算後是否清空重來),getResult 則用 eval 直接計算表達式並把結果接回顯示,是理解 eval 應用的小範例。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved