本篇文章给大家带来的内容是介绍 JS 实现简单的计算器功能(附代码). 有一定的参考价值, 有需要的朋友可以参考一下, 希望对大家有所帮助.
实现基本计算器功能, 如图
逻辑代码
- <!DOCTYPE html>
- <HTML>
- <head>
- <meta charset="UTF-8">
- <title>
- 计算器
- </title>
- <!-- 设置样式 -->
- <style>
- .showdiv{ text-align: center; margin:auto;/* 设置居中 */ border: solid 1px;
- width: 400px; height: 500px; border-radius: 10px;/* 设置边框角度 */ } input[type="text"]{
- margin-top: 10px; width: 380px; height: 40px; font-size: 40px; } input[type="button"]{
- margin: 10px; margin-top: 20px; width: 60px; height: 80px; font-size: 40px;
- font-weight: bold; }
- </style>
- <!-- 设置 js 代码 -->
- <script type="text/javascript">
- /* 将按钮的值赋值给输入框 */
- function num(btn) {
- // 把不能为零去掉
- if (document.getElementById("inp").value.match("除数")) {
- document.getElementById("inp").value = "";
- }
- // 获取 button 按钮的 value
- var num = btn.value;
- console.log(num + " " + typeof(num))
- // 将值赋值给 text 文本框
- switch (num) {
- case "c":
- document.getElementById("inp").value = "";
- break;
- case "=":
- if (document.getElementById("inp").value.match("/")) {
- if (document.getElementById("inp").value.split("/")[1] == "0") {
- document.getElementById("inp").value = "除数不能为零";
- } else {
- document.getElementById("inp").value = eval(document.getElementById("inp").value);
- }
- break;
- } else {
- document.getElementById("inp").value = eval(document.getElementById("inp").value);
- break;
- }
- default:
- document.getElementById("inp").value = document.getElementById("inp").value + num;
- break;
- }
- }
- </script>
- </head>
- <body>
- <div class="showdiv">
- <input type="text" name="" id="inp" value="" readonly="readonly" />
- <br />
- <input type="button" name="" id="" value="0" onclick="num(this)" />
- <input type="button" name="" id="" value="1" onclick="num(this)" />
- <input type="button" name="" id="" value="2" onclick="num(this)" />
- <input type="button" name="" id="" value="3" onclick="num(this)" />
- <br />
- <input type="button" name="" id="" value="4" onclick="num(this)" />
- <input type="button" name="" id="" value="5" onclick="num(this)" />
- <input type="button" name="" id="" value="6" onclick="num(this)" />
- <input type="button" name="" id="" value="7" onclick="num(this)" />
- <br />
- <input type="button" name="" id="" value="8" onclick="num(this)" />
- <input type="button" name="" id="" value="9" onclick="num(this)" />
- <input type="button" name="" id="" value="+" onclick="num(this)" />
- <input type="button" name="" id="" value="-" onclick="num(this)" />
- <br />
- <input type="button" name="" id="" value="*" onclick="num(this)" />
- <input type="button" name="" id="" value="/" onclick="num(this)" />
- <input type="button" name="" id="" value="=" onclick="num(this)" />
- <input type="button" name="" id="" value="c" onclick="num(this)" />
- </div>
- </body>
- </HTML>
更多 web 开发 https://www.html.cn/ 知识, 请查阅 HTML 中文网 !!
来源: http://www.css88.com/web/javascript/17439.html