发布时间:2016-07-07 12:51:47 作者:佚名 阅读:(864)
<!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; }
欢迎分享转载→ 使用PHP开发一个简易计算器,实现加减乘除等功能
Deprecated: Methods with the same name as their class will not be constructors
(2786)人喜欢 2022-04-19if condition多个值_thinkphp if标签的condition用法
(2940)人喜欢 2022-04-19PHP获取今日、昨日、上周、本月的起始时间戳和结束时间戳的方法
(54)人喜欢 2019-06-11PHP判断是否是序列化字符串数据的函数
(1440)人喜欢 2015-11-21php数组排序详解
(34)人喜欢 2015-11-21php文件怎么打开
(252)人喜欢 2015-11-21© 2015-2021 - 吾爱编程网 版权所有 苏ICP备18033726号-1关于我们 - 网站声明 - 联系我们