<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>計算器</title>
<link rel="stylesheet" type="text/css" href="calculator.css">
</head>
<body>
<div class="input-box" id="input-box">
<form method="post" action="" onsubmit="return fullEmpty();">
<h3>PHP版簡單計算器</h3>
<input type="text" name="a" id="a">
<select name="oprt" id="oprt">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
<option value="%">%</option>
</select>
<input type="text" name="b" id="b">
<button type="submit" name="submit">計算</button>
</form>
</div>
<div class="result" id="result"></div>
</body>
<script type="text/javascript" src="calculator.js"></script>
<?php
if(isset($_POST["a"]) && isset($_POST["b"]) && isset($_POST["oprt"])) {
$a = $_POST["a"]; //第一個參加運算的數
$b = $_POST["b"]; //第二個參加運算的數
$oprt = $_POST["oprt"]; //運算符
$r = ""; //運算結果
//輸入框記憶功能
echo "<script>".
"a.value = '{$a}';".
"b.value = '{$b}';".
"oprt.value = '{$oprt}';".
"</script>";
if (!is_numeric($a) || !is_numeric($b)) {
$r = "運算符兩邊必須是數字";
} else {
$a = $a - 0;
$b = $b - 0;
switch($oprt) {
case "+":
$r = $a + $b;
break;
case "-":
$r = $a - $b;
break;
case "*":
$r = $a * $b;
break;
case "/":
if($b == 0) {
$r = "除數不能為0";
} else {
$r = $a / $b;
}
break;
case "%":
if(!is_int($a) || !is_int($b)) {
$r = "求余運算符兩邊必須是整數";
} else if($b == 0) {
$r = "除數不能為0";
} else {
$r = $a % $b;
}
break;
default:
break;
}
}
//如果運算結果是數字,說明輸入正常,否則提示輸入錯誤信息
if(is_numeric($r)) {
echo "<script>result.innerText = '{$a} {$oprt} {$b} = {$r}';</script>";
} else {
echo "<script>result.innerText = '{$r}';</script>";
}
}
?>
</html>
JavaScript
var result = document.getElementById("result");
var a = document.getElementById("a");
var b = document.getElementById("b");
var oprt = document.getElementById("oprt");
//當用戶試圖提交表單時判斷輸入是否為空
function fullEmpty() {
if(a.value.length < 1 || b.value.length < 1) {
alert("輸入不能為空");
return false;
}
return true;
}
CSS
*{
margin: 0;
padding: 0;
}
.input-box{
width: 320px;
margin: 20px auto 0;
overflow: hidden;
}
.input-box h3{
width: 100%;
text-align: center;
}
.input-box input, select, button{
margin-top: 10px;
}
.input-box input{
width: 100px;
}
.input-box select, button{
width: 50px;
}
.result{
width: 318px;
height: 100px;
border: 1px solid #ccc;
margin: 10px auto 0;
text-align: left;
}
*