HTML5+css+JavaScript进行四则运算简易计算器(用按钮实现)
javascript实现简易计算器的代码_
javascript实现简易计算器的代码_ 下面我就为大家带来一篇javascript实现简易计算器的代码我觉得挺不错的,现在分享给大家,也给大家做个参考。
今日闲来无聊,想写点什么,突然想到用javascript写一个计算器。
程序还存在许多的Bug,先在这里记录一下,以后慢慢更正。
代码如下:!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "l1/DTD/xhtml1-transitional.dtd" html xmlns="l"headmeta http-equiv="Content-Type" content="text/html; charset=utf-8" /titlejavascript实现简易计算器的代码_脚本之家/titlestyle type="text/css"input{width:30px;height:20px;text-align:center;}#tbCalculator td{text-align:center;vertical-align:middle;}/stylescript type="text/javascript"var result; //保存点击运算符之前输入框中的数值var operator; //保存运算符var isPressEqualsKey = false; //记录是否按下”=“键 //数字键大事function connectionDigital(control){var txt = document.getElementById('txtScream'); if(isPressEqualsKey){txt.value = ""; //已进行过计算,则清空数值输入框重新开头isPressEqualsKey = false;}//数值输入已经存在小数点,则不允许再输入小数点if(txt.value.indexOf('.') -1 control.value == '.')return false;txt.value += control.value; //将控件值赋给数值输入框中}//退格键大事function backspace(){var txt = document.getElementById('txtScream'); txt.value = txt.value.substring(0,txt.value.length - 1);}//ce键大事:清空数字输入框function clearAll(){document.getElementById('txtScream').value = ""; result = "";operator = "";}// +、-、*、/ 大事function calculation(control){//将运算符保存入全局变量中operator = control.value;var txt = document.getElementById('txtScream'); if(txt.value == "")return false; //数值输入框中没有数字,则不能输入运算符//将数值输入框中的值保存到计算表达式中result = txt.value;//清空输入框,以待输入操作值txt.value = "";}//计算结果function getResult(){var opValue;//计算表达式中存在运算符var sourseValue = parseFloat(result);var txt = document.getElementById('txtScream'); if(operator == '*')opValue = sourseValue * parseFloat(txt.value); else if(operator == '/')opValue = sourseValue / parseFloat(txt.value);else if(operator == '+')opValue = sourseValue + parseFloat(txt.value);else if(operator == '-')opValue = sourseValue - parseFloat(txt.value);txt.value = opValue;isPressEqualsKey = true;result = "";opValue = "";}/script/headbodytable id="tbCalculator" width="200" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#0066FF"trtd height="30" colspan="4" align="center"input type="text" name="txtScream" id="txtScream" style="width:180px; border-style:none; text-align:right;" readonly="readonly" / /td/trtrtd height="30" colspan="2"input type="button" name="btnCE" id="btnCE" value="C E" style="width:80px;" align="right"; onclick="clearAll();" //tdtd height="30" colspan="2"input type="button" name="btn10" id="btn10" value="Backspace" style="width:80px;" align="right"; onclick="backspace();" //td/trtrtd height="30"input type="button" name="btn7" id="btn7" value="7" onclick="connectionDigital(this);" //tdtdinput type="button" name="btn8" id="btn8" value="8" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn9" id="btn9" value="9" onclick="connectionDigital(this);" //td tdinput type="button" name="btn6" id="btn6" value="/" onclick="calculation(this);" //td/trtrtd height="30"input type="button" name="btn4" id="btn4" value="4" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn5" id="btn5" value="5" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn6" id="btn6" value="6" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn13" id="btn13" value="*" onclick="calculation(this);" //td/trtrtd height="30"input type="button" name="btn1" id="btn1" value="1" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn2" id="btn2" value="2" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn3" id="btn3" value="3" onclick="connectionDigital(this);"//tdtdinput type="button" name="btn18" id="btn18" value="-" onclick="calculation(this);" //td/trtrtd height="30"input type="button" name="btn0"id="btn0" value="0" onclick="connectionDigital(this);"//tdtdinput type="button" name="btndot" id="btndot" value="." onclick="connectionDigital(this);" //td tdinput name="btn22" type="button" id="btn22" value="=" onclick="getResult();" //tdtdinput type="button" name="btn23" id="btn23" value="+" onclick="calculation(this);" //td/tr/table/body/html以上这篇javascript实现简易计算器的代码就是我分享给大家的全部内容了,盼望能给大家一个参考...。
javascript代码实现简易计算器
javascript代码实现简易计算器本⽂实例为⼤家分享了javascript实现简易计算器的具体代码,供⼤家参考,具体内容如下编辑了⼏个⼩时研发了⼀个简易好理解的计算器。
不停改Bug,终于改好了。
这是样式这是Css部分<style>#box {background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);width: 500px;height: 420px;margin: auto;margin-top: 200px;position: relative;}.reckon {width: 280px;height: 200px;background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%);;position: absolute;top: 100px;left: 100px;border: 5px solid #2a2b2c}#input1 {background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);border: none;width: 220px;height: 8px;float: right;margin-top: 10px;margin-right: 20px;outline: none;padding: 10px}ul li {float: left;list-style: none;margin: 4px 2px;border-radius: 3px;background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);box-shadow: 2px 2px #ccc;color: #fff;font-weight: "楷体";width: 50px;height: 30px;text-align: center;line-height: 30px;}ul {margin-top: 5px;}ul li:hover {opacity: 0.7;}</style>这是HTML部分<div id="box"><div class="reckon" id="reckon"><input type="text" id="input1"><ul><li class="num">7</li><li class="num">8</li><li class="num">9</li><li class="opcr">+</li><li class="num">4</li><li class="num">5</li><li class="num">6</li><li class="opcr">- </li><li class="num">1</li><li class="num">2</li><li class="num">3</li><li class="opcr">*</li><li class="num">0</li><li id="returnZero">C</li><li id="resule">=</li><li class="opcr">/</li></ul></div></div>/* 定义两个标签来存放符号跟第⼀个值*/<input type="text" id="text1" style="display:none"><input type="text" id="per" style="display:none">html部分的话就是吧所有数字定义为⼀个class名字,把所有运算符号定义为⼀个class 以及定义两个input来存放运算符<script>lis = document.querySelectorAll("#box ul .num")//获取所有的数字opcr = document.querySelectorAll("#box ul .opcr")//获取运算符for (var i = 0; i < lis.length; i++) { //遍历所有的数字lis[i].onclick = function () {input1.value += parseInt(this.innerHTML)//点击input1显⽰}}//遍历所有的运算符for (let i = 0; i < opcr.length; i++) {opcr[i].onclick = function () {if (text1.value == "") {//当存放第⼀个值为空时候text1.value = input1.value//存放第⼀个值input1.value = "" //input框⾥的值为空per.value = this.innerHTML; //存放符号的值为空} else {text1.value = eval(text1.value + per.value + input1.value)//不是空的时候计算per.value = this.innerHTML;//存放符号的值为点击的值input1.value = ""//input框⾥的值为空}}}//等于resule.onclick = function () {input1.value = eval(text1.value + per.value + input1.value)//计算⾥⾯的值 per.value = "" //清空存放per的值text1.value = ""//input框⾥的值为空}//点击清空所有returnZero.onclick = function () {input1.value = ""per.value = ""text1.value = ""}</script>完整部分<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"><title>简易计算器</title><style>#box {background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%); width: 500px;height: 420px;margin: auto;margin-top: 200px;position: relative;}.reckon {width: 280px;height: 200px;background-image: linear-gradient(120deg, #d4fc79 0%, #96e6a1 100%); ;position: absolute;top: 100px;left: 100px;border: 5px solid #2a2b2c}#input1 {background-image: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);border: none;width: 220px;height: 8px;float: right;margin-top: 10px;margin-right: 20px;outline: none;padding: 10px}ul li {float: left;list-style: none;margin: 4px 2px;border-radius: 3px;background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%); box-shadow: 2px 2px #ccc;color: #fff;font-weight: "楷体";width: 50px;height: 30px;text-align: center;line-height: 30px;}ul {margin-top: 5px;}opacity: 0.7;}</style></head><body><div id="box"><div class="reckon" id="reckon"><input type="text" id="input1"><ul><li class="num">7</li><li class="num">8</li><li class="num">9</li><li class="opcr">+</li><li class="num">4</li><li class="num">5</li><li class="num">6</li><li class="opcr">- </li><li class="num">1</li><li class="num">2</li><li class="num">3</li><li class="opcr">*</li><li class="num">0</li><li id="returnZero">C</li><li id="resule">=</li><li class="opcr">/</li></ul></div></div><input type="text" id="text1" style="display:block"><input type="text" id="per" style="display:block"><script>lis = document.querySelectorAll("#box ul .num")//获取所有的数字opcr = document.querySelectorAll("#box ul .opcr")//获取+——*/for (var i = 0; i < lis.length; i++) { //遍历所有的数字lis[i].onclick = function () {input1.value += parseInt(this.innerHTML)//点击input1显⽰}}//遍历所有的+——*/for (let i = 0; i < opcr.length; i++) {opcr[i].onclick = function () {if (text1.value == "") {//当存放第⼀个值为空时候text1.value = input1.value//存放第⼀个值input1.value = "" //input框⾥的值为空per.value = this.innerHTML; //存放符号的值为空} else {text1.value = eval(text1.value + per.value + input1.value)//不是空的时候计算值 per.value = this.innerHTML;//存放符号的值为点击的值input1.value = ""//input框⾥的值为空}}}//等于resule.onclick = function () {input1.value = eval(text1.value + per.value + input1.value)//计算⾥⾯的值per.value = "" //清空存放per的值text1.value = ""//input框⾥的值为空}//点击清空所有returnZero.onclick = function () {input1.value = ""per.value = ""text1.value = ""}</script></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
JS实现简易计算器的7种方法
JS实现简易计算器的7种⽅法先放图(好吧⽐较挫)⽅法⼀:最容易版<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" onclick="addHandler();" /><input type="button" value="-" onclick="subtractHandler();" /><input type="button" value="×" onclick="multiplyHandler();" /><input type="button" value="÷" onclick="divideHandler();" /></p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');// 加function addHandler() {sign.innerHTML = '+';resultOutput.innerHTML = +formerInput.value + +laterInput.value;}// 减function subtractHandler() {sign.innerHTML = '-';resultOutput.innerHTML = formerInput.value - laterInput.value;}// 乘function multiplyHandler() {sign.innerHTML = '×';resultOutput.innerHTML = formerInput.value * laterInput.value;}// 除function divideHandler() {sign.innerHTML = '÷';resultOutput.innerHTML = formerInput.value / laterInput.value;}</script></body></html>⽅法⼆:结构和⾏为分离<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title>#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" onclick="addHandler();" /><input type="button" value="-" onclick="subtractHandler();" /><input type="button" value="×" onclick="multiplyHandler();" /><input type="button" value="÷" onclick="divideHandler();" /></p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');var btns = calculator.querySelectorAll('.btn');// 绑定事件// +btns[0].onclick = addHandler;// -btns[1].onclick = subtractHandler;// ×btns[2].onclick = multiplyHandler;// ÷btns[3].onclick = divideHandler;// 加function addHandler() {sign.innerHTML = '+';resultOutput.innerHTML = +formerInput.value + +laterInput.value; }// 减function subtractHandler() {sign.innerHTML = '-';resultOutput.innerHTML = formerInput.value - laterInput.value;}// 乘function multiplyHandler() {sign.innerHTML = '×';resultOutput.innerHTML = formerInput.value * laterInput.value;}// 除function divideHandler() {sign.innerHTML = '÷';resultOutput.innerHTML = formerInput.value / laterInput.value;}</script></body></html>⽅法三:循环绑定事件<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;<!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" onclick="addHandler();" /><input type="button" value="-" onclick="subtractHandler();" /><input type="button" value="×" onclick="multiplyHandler();" /><input type="button" value="÷" onclick="divideHandler();" /></p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');var btns = calculator.querySelectorAll('.btn');// 绑定事件for (var i = 0; i < btns.length; i++) {btns[i].onclick = function () {switch (this.title) {case 'add':addHandler();break;case 'subtract':subtractHandler();break;case 'multiply':multiplyHandler();break;case 'divide':divideHandler();break;}};}// 加function addHandler() {sign.innerHTML = '+';resultOutput.innerHTML = +formerInput.value + +laterInput.value; }// 减function subtractHandler() {sign.innerHTML = '-';resultOutput.innerHTML = formerInput.value - laterInput.value;}// 乘function multiplyHandler() {sign.innerHTML = '×';resultOutput.innerHTML = formerInput.value * laterInput.value;}// 除function divideHandler() {sign.innerHTML = '÷';resultOutput.innerHTML = formerInput.value / laterInput.value;}</script></body></html>⽅法四:提取函数<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /> <input type="button" value="×" class="btn" title="multiply" /> <input type="button" value="÷" class="btn" title="divide" /> </p></div><script>// 获取元素var calculator = document.querySelector('#calculator');var formerInput = calculator.querySelector('.formerInput');var laterInput = calculator.querySelector('.laterInput');var sign = calculator.querySelector('.sign');var resultOutput = calculator.querySelector('.resultOutput');var btns = calculator.querySelectorAll('.btn');// 绑定事件each(btns, function (index, elem ) {elem.onclick = function () {switch (this.title) {case 'add':addHandler();break;case 'subtract':subtractHandler();break;case 'multiply':multiplyHandler();break;case 'divide':divideHandler();break;}};});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {sign.innerHTML = symbol;}// 加法function add(num1, num2) {return +num1 + +num2;}// 减法function subtract(num1, num2) {return num1 - num2;}// 乘法function multiply(num1, num2) {return num1 * num2;}// 除法function divide(num1, num2) {return num1 / num2;}// 输出结果}// 加function addHandler() {// sign.innerHTML = '+';updateSign('+');outputResult(add(formerInput.value, laterInput.value));}// 减function subtractHandler() {updateSign('-');outputResult(subtract(formerInput.value, laterInput.value)); }// 乘function multiplyHandler() {updateSign('×');outputResult(multiply(formerInput.value, laterInput.value)); }// 除function divideHandler() {updateSign('÷');outputResult(divide(formerInput.value, laterInput.value)); }</script></body></html>⽅法五:管理代码(找到组织)<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /> <input type="button" value="×" class="btn" title="multiply" /> <input type="button" value="÷" class="btn" title="divide" /> </p></div><script>// 获取元素var wrapElem = document.querySelector('#calculator');var calculatorElem = {formerInput: wrapElem.querySelector('.formerInput'),laterInput: wrapElem.querySelector('.laterInput'),sign: wrapElem.querySelector('.sign'),resultOutput: wrapElem.querySelector('.resultOutput'), btns: wrapElem.querySelectorAll('.btn')};// 绑定事件each(calculatorElem.btns, function (index, elem ) {elem.onclick = function () {switch (this.title) {case 'add':addHandler();break;case 'subtract':multiplyHandler();break;case 'divide':divideHandler();break;}};});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {calculatorElem.sign.innerHTML = symbol;}var operation = {add: function(num1, num2) {return +num1 + +num2;},subtract: function(num1, num2) {return num1 - num2;},multiply: function(num1, num2) {return num1 * num2;},divide: function(num1, num2) {return num1 / num2;}};// 输出结果function outputResult(result) {calculatorElem.resultOutput.innerHTML = result;}// 加function addHandler() {// sign.innerHTML = '+';updateSign('+');outputResult(operation.add(calculatorElem.formerInput.value, terInput.value));}// 减function subtractHandler() {updateSign('-');outputResult(operation.subtract(calculatorElem.formerInput.value, terInput.value)); }// 乘function multiplyHandler() {updateSign('×');outputResult(operation.multiply(calculatorElem.formerInput.value, terInput.value)); }// 除function divideHandler() {updateSign('÷');outputResult(operation.divide(calculatorElem.formerInput.value, terInput.value)); }</script></body></html>⽅法六:OCP开放--封闭原则<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /><input type="button" value="×" class="btn" title="multiply" /><input type="button" value="÷" class="btn" title="divide" /><input type="button" value="%" class="btn" title="mod" /><input type="button" value="^" class="btn" title="power" /><!-- <input type="button" value="1/x" class="btn" title="invert" /> --></p></div><script>// 获取元素var wrapElem = document.querySelector('#calculator');var calculatorElem = {formerInput: wrapElem.querySelector('.formerInput'),laterInput: wrapElem.querySelector('.laterInput'),sign: wrapElem.querySelector('.sign'),resultOutput: wrapElem.querySelector('.resultOutput'),btns: wrapElem.querySelectorAll('.btn')};// 绑定事件each(calculatorElem.btns, function (index, elem ) {elem.onclick = function () {updateSign(this.value);outputResult(operate(this.title, calculatorElem.formerInput.value, terInput.value)); };});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {calculatorElem.sign.innerHTML = symbol;}// 运算function operate(name, num1, num2) {if (!operation[name]) throw new Error('不存在名为' + name + '的运算⽅法!');return operation[name](num1, num2);}var operation = {add: function(num1, num2) {return +num1 + +num2;},subtract: function(num1, num2) {return num1 - num2;},multiply: function(num1, num2) {return num1 * num2;},divide: function(num1, num2) {return num1 / num2;},addOperation: function (name, fn) {if (!this[name]) {this[name] = fn;}return this;}};operation.addOperation('mod', function (num1, num2) {return num1 % num2;}).addOperation('power', function (base, power) {return Math.pow(base, power);function outputResult(result) {calculatorElem.resultOutput.innerHTML = result;}</script></body></html>⽅法七:模块化<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8" /><title>简易计算器</title><style>body {background-color: #eee;}#calculator {margin: 100px 0 0 150px;}</style></head><body><!-- 简易计算器 --><div id="calculator"><p><input type="text" class="formerInput" value="1" /><span class="sign">+</span><input type="text" class="laterInput" value="1" /><span>=</span><span class="resultOutput">2</span></p><p><input type="button" value="+" class="btn" title="add" /><input type="button" value="-" class="btn" title="subtract" /><input type="button" value="×" class="btn" title="multiply" /><input type="button" value="÷" class="btn" title="divide" /><input type="button" value="%" class="btn" title="mod" /><input type="button" value="^" class="btn" title="power" /><input type="button" value="1/x" class="btn" title="invert" /></p></div><script>(function () {// 获取元素var wrapElem = document.querySelector('#calculator');var calculatorElem = {formerInput: wrapElem.querySelector('.formerInput'),laterInput: wrapElem.querySelector('.laterInput'),sign: wrapElem.querySelector('.sign'),resultOutput: wrapElem.querySelector('.resultOutput'),btns: wrapElem.querySelectorAll('.btn')};// 绑定事件each(calculatorElem.btns, function (index, elem ) {elem.onclick = function () {updateSign(this.value);outputResult(operate(this.title, calculatorElem.formerInput.value, terInput.value)); };});// 遍历function each(array, fn) {for (var i = 0; i < array.length; i++) {fn(i, array[i]);}}// 更新符号function updateSign(symbol) {calculatorElem.sign.innerHTML = symbol;}// 运算var operate = (function () {subtract: function(num1, num2) {return num1 - num2;},multiply: function(num1, num2) {return num1 * num2;},divide: function(num1, num2) {return num1 / num2;},addOperation: function (name, fn) {if (!operation[name]) {operation[name] = fn;}return operation;}};function operate(name) {if (!operation[name]) throw new Error('不存在名为' + name + '的运算⽅法!');return operation[name].apply(operation, [].slice.call(arguments, 1, arguments.length)); }operate.addOperation = operation.addOperation;return operate;})();operate.addOperation('mod', function (num1, num2) {return num1 % num2;}).addOperation('power', function (base, power) {return Math.pow(base, power);}).addOperation('invert', function (num) {return 1 / num;});// 输出结果function outputResult(result) {calculatorElem.resultOutput.innerHTML = result;}})();</script></body></html>。
JavaScript实现简单的四则运算计算器完整实例
JavaScript实现简单的四则运算计算器完整实例本⽂实例讲述了JavaScript实现简单的四则运算计算器。
分享给⼤家供⼤家参考,具体如下:运⾏效果图如下:完整实例代码如下:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>computer</title><script>function compute(){str1=Number(document.getElementById("txt1").value);str2=Number(document.getElementById("txt2").value);comp=document.getElementById("select").value;var result;switch(comp) {case "+":comp=str1+str2;break;case "-":comp=str1-str2;break;case "*":comp=str1*str2;break;case "/":if(str2==0){alert("除数不能为0!");comp='';}else{comp=str1/str2;}break;}document.getElementById("result").value=comp;}</script></head><body><input type="text" id="txt1"/><select name="method" id="select"><option value="+">+</option><option value="-">-</option><option value="*">*</option><option value="/">/</option></select><input type="text" id="txt2"/><input type="button" id="b1" value="等于" onclick="compute()" /><input type="text" id="result"/></body></html>PS:这⾥再为⼤家推荐⼏款计算⼯具供⼤家进⼀步参考借鉴:更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》及《》希望本⽂所述对⼤家JavaScript程序设计有所帮助。
js实现四则混合运算计算器
js实现四则混合运算计算器最近想⽤js做⼀个简单的计算器,不过⽹上的例⼦好像⼤部分都是直接从左到右挨个计算,就好像1+2*5,就会先计算1+2,再计算3*5,并没有实现运算符的优先级,这⾥找到了⼀种⽅法实现,来总结⼀下。
不过这⾥只是最基本的思路,还有许许多多的细节没有完善。
在解决基本的样式布局与交互逻辑之前,我们先来解决四则混合运算的核⼼模块,也就是如何把我们输⼊的字符串转换为数字表达式并进⾏计算:我所找到的⽅法叫做逆波兰表达式(也叫做后缀表达式),关于逆波兰表达式的具体定义⼤家可以上⽹去搜索⼀下,概念应该⽐较简单。
这⾥我们举⼀个例⼦来展⽰⼀下逆波兰表达式的作⽤:例如:3+4*5 ,这个表达式要如何实现先算乘号再算加号呢?对于计算机来说应该很难实现但是把它转换成这个式⼦再看⼀下:3,4,5,*,+,那么这样看起来好像就简单多了,只要每遇到⼀个操作符就将他的前两个操作数进⾏运算,再将操作结果代替运算表达式直到算出最终结果,这样说有点复杂,我们还是看⼀下例⼦3,4,5,*,+ -> 3,20,+ -> 23那么该如何把我们熟悉的 3+4*5 转变成这个⽜逼的逆波兰表达式呢?⼤家也可以上⽹搜索⼀下,这⾥我给出⼀个我找到的链接:为了⽅便⼤家顺畅的浏览⽂章,这⾥截取⽂章的部分核⼼内容(即转换规则):⼀般算法:逆波兰表达式的⼀般解析算法是建⽴在简单算术表达式上的,它是我们进⾏公式解析和执⾏的基础:1. 构建两个栈Operand(操作数栈)和Operator(操作符栈)。
2.扫描给定的字符串,如果得到⼀个数字,则提取(扫描是⼀位⼀位的,⼀定要提取⼀个完整的数字)数字(以下⽤Operand代替),然后把Operand压⼊Operand栈中。
3. 如果获得⼀个运算符(⽐如+或者*,下⾯⽤B代替),则需要和Operator栈栈顶元素(⽤A替代)⽐较:1) 如果A不存在,则把B压⼊Operator栈中;2)如果B是⼀个左括号,则忽略A和B的优先级⽐较,把B压⼊Operator栈。
信息技术作业使用JavaScript实现一个简单的计算器程序
信息技术作业使用JavaScript实现一个简单的计算器程序使用JavaScript实现一个简单的计算器程序JavaScript是一种广泛用于网页开发的脚本语言,可以方便地与HTML结合使用。
在本篇文章中,我们将使用JavaScript编写一个简单的计算器程序。
该程序将具备基本的加减乘除功能,以及清零和回退操作。
程序实现的核心是通过JavaScript的事件监听机制,监听用户的点击事件,并根据点击按钮的不同进行相应的处理。
下面是具体的实现步骤:1. 页面布局首先,我们需要在HTML中搭建计算器的基本界面。
可以使用HTML的表格元素来实现计算器的按钮布局,如下所示:```html<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>简单计算器</title><script src="calculator.js"></script></head><body><table><tr><td colspan="4"><input type="text" id="result" readonly></td> </tr><tr><td><button onclick="appendNumber(7)">7</button></td><td><button onclick="appendNumber(8)">8</button></td><td><button onclick="appendNumber(9)">9</button></td><td><button onclick="appendOperator('+')">+</button></td> </tr><tr><td><button onclick="appendNumber(4)">4</button></td><td><button onclick="appendNumber(5)">5</button></td><td><button onclick="appendNumber(6)">6</button></td><td><button onclick="appendOperator('-')">-</button></td></tr><tr><td><button onclick="appendNumber(1)">1</button></td> <td><button onclick="appendNumber(2)">2</button></td> <td><button onclick="appendNumber(3)">3</button></td> <td><button onclick="appendOperator('*')">*</button></td> </tr><tr><td><button onclick="appendNumber(0)">0</button></td> <td><button onclick="appendNumber('.')">.</button></td> <td><button onclick="calculate()">=</button></td><td><button onclick="appendOperator('/')">/</button></td> </tr><tr><td colspan="4"><button onclick="clearResult()">清零</button></td></tr><tr><td colspan="4"><button onclick="backspace()">回退</button></td></tr></table></body></html>```在上面的代码中,我们使用`<input>`元素来显示计算结果,使用`<button>`元素来作为按钮,通过调用相应的JavaScript函数来执行对应的操作。
JS实现简易计算器
JS实现简易计算器⽤JS实现简易计算器,供⼤家参考,具体内容如下⾸先创建结构和样式<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>body{margin:0;padding:0;background-color: #abcdef;}.cal{width:560px;height:100px;margin:0 auto;padding-top:300px;}</style></head><body><div class="cal"><p><input type="text" class="num1" value="1"><span class="sign">+</span><input type="text" class="num2" value="1"><span>=</span><span class="res">2</span></p><p><input type="button" value="+"><input type="button" value="-"><input type="button" value="*"><input type="button" value="/"></p></div><script></script></body></html>然后添加Java script<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>body{margin:0;padding:0;background-color: #abcdef;}.cal{width:560px;height:100px;margin:0 auto;padding-top:300px;}</style></head><body><div class="cal"><p><input type="text" class="num1" value="1"><span class="sign">+</span><input type="text" class="num2" value="1"><span>=</span><span class="res">2</span></p><p><input type="button" value="+" class="btn"><input type="button" value="-" class="btn"><input type="button" value="*" class="btn"><input type="button" value="/" class="btn"></p></div><script>var cal=document.querySelector(".cal");var num1=cal.querySelector(".num1");var num2=cal.querySelector(".num2");var sign=cal.querySelector(".sign");var res=cal.querySelector(".res");var btns=cal.querySelectorAll(".btn");btns[0].onclick=add;btns[1].onclick=subtract;btns[2].onclick=multiply;btns[3].onclick=divide;function add(){sign.innerHTML="+";//由于DOM获取到的值都是字符串形式,因此进⾏操作时需要先转为number类型 res.innerHTML=Number(num1.value)+Number(num2.value);}function subtract(){sign.innerHTML="-";res.innerHTML=Number(num1.value)-Number(num2.value);}function multiply(){sign.innerHTML="*";res.innerHTML=Number(num1.value)*Number(num2.value);}function divide(){sign.innerHTML="/";res.innerHTML=Number(num1.value)/Number(num2.value);}</script></body></html>代码的优化:循环实现绑定给⼀个外部接⼝,⽤于新增运算<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>body{margin:0;padding:0;background-color: #abcdef;}.cal{width:560px;height:100px;margin:0 auto;padding-top:300px;}</style></head><body><div class="cal"><p><input type="text" class="num1" value="1"><span class="sign">+</span><input type="text" class="num2" value="1"><span>=</span><span class="res">2</span></p><p><input type="button" value="+" class="btn" title="add"><input type="button" value="-" class="btn" title="subtract"><input type="button" value="*" class="btn" title="multiply"><input type="button" value="/" class="btn" title="divide"><input type="button" value="%" class="btn" title="mod"></p></div><script>var cal=document.querySelector(".cal");var num1=cal.querySelector(".num1");var num2=cal.querySelector(".num2");var sign=cal.querySelector(".sign");var res=cal.querySelector(".res");var btns=cal.querySelectorAll(".btn");//给每个按钮绑定事件for(var i=0;i<btns.length;i++){operate(i);}//运算函数function operate(i){var op=btns[i].value;//获取运算var opName=btns[i].title;//获取运算名//绑定事件btns[i].onclick=function(){sign.innerHTML=op;res.innerHTML=operation[opName](Number(num1.value),Number(num2.value)); }}var operation={add:function(n1,n2){return n1+n2;},subtract:function(n1,n2){return n1-n2;},multiply:function(n1,n2){return n1*n2;},divide:function(n1,n2){return n1/n2;},//给⼀个新增运算的接⼝addOperation:function(name,fn){//如果该运算不存在if(!){this[name]=fn;}}}//新增取余运算operation.addOperation("mod",function(n1,n2){return n1%n2;});</script></body></html>这样就圆满完成咯以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
JavaScript实现简单计算器
JavaScript实现简单计算器适合初学者参考的简易计算器,⾥⾯没有太多的难以理解的⽅法,使⽤的是最基础的JS语法解决式⼦的运算问题,同时处理了式⼦中的运算优先级。
实现思路1、通过绑定点击事件实现待计算式⼦的输⼊2、遍历原式⼦,读取式⼦中乘除运算符的位置3、优先处理乘除取余运算4、处理加减运算5、返回结果代码:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>Document</title></head><body><!-- 计算器 --><style>.work2{width: 500px;margin-top: 50px;}h2{color: #333;}#work2Article1{width: 100%;height: 200px;background: #cccccc;font-size: 20px;}#work2Article2{width: 100%;height: 400px;background: #cccccc;}#work2Article2 button{width: 24.1%;height: 20%;color: #333;background: #999;}.work2 button{font-size: 20px;}</style><section class="work2"><h2>计算器</h2><article id="work2Article1"></article><article id="work2Article2"><button id="work2BtnCle">AC</button><button id="work2BtnDel">×</button><button id="work2BtnRem">%</button><button id="work2BtnDiv">/</button><button id="work2Btn7">7</button><button id="work2Btn8">8</button><button id="work2Btn9">9</button><button id="work2BtnMul">*</button><button id="work2Btn4">4</button><button id="work2Btn5">5</button><button id="work2Btn6">6</button><button id="work2BtnSub">-</button><button id="work2Btn1">1</button><button id="work2Btn2">2</button><button id="work2Btn3">3</button><button id="work2BtnAdd">+</button><button id="work2BtnNull">未开发</button><button id="work2Btn0">0</button><button id="work2BtnPoi">.</button><button id="work2BtnEqu">=</button></article></section><script>var num = "0"; //输⼊的原式var res = 0 ; //结果var work2Article1 = document.getElementById('work2Article1'); var work2BtnCle = document.getElementById('work2BtnCle'); var work2BtnDiv = document.getElementById('work2BtnDiv'); var work2BtnDel = document.getElementById('work2BtnDel'); var work2BtnRem = document.getElementById('work2BtnRem'); var work2BtnMul = document.getElementById('work2BtnMul'); var work2BtnSub = document.getElementById('work2BtnSub'); var work2BtnAdd = document.getElementById('work2BtnAdd'); var work2BtnNull = document.getElementById('work2BtnNull'); var work2BtnPoi = document.getElementById('work2BtnPoi'); var work2BtnEqu = document.getElementById('work2BtnEqu'); var work2Btn1 = document.getElementById('work2Btn1');var work2Btn2 = document.getElementById('work2Btn2');var work2Btn3 = document.getElementById('work2Btn3');var work2Btn4 = document.getElementById('work2Btn4');var work2Btn5 = document.getElementById('work2Btn5');var work2Btn6 = document.getElementById('work2Btn6');var work2Btn7 = document.getElementById('work2Btn7');var work2Btn8 = document.getElementById('work2Btn8');var work2Btn9 = document.getElementById('work2Btn9');var work2Btn0 = document.getElementById('work2Btn0');// 初始化work2BtnCle.onclick = function () {num = "0" ;work2Article1.innerText=`${num}`;}work2BtnDel.onclick = function () {// 判断原式长度,长度为1时变为0if(num.length==1){num = '0' ;work2Article1.innerText=num;// 否则减去最后⼀位}else{num = num.substring(0,num.length-1);work2Article1.innerText=num;}}// 运算符点击事件work2BtnDiv.onclick = function () {num += "/"work2Article1.innerText=num;}work2BtnRem.onclick = function () {num += "%" ;work2Article1.innerText=`${num}`;}work2BtnMul.onclick = function () {num += "*" ;work2Article1.innerText=`${num}`;}work2BtnAdd.onclick = function () {num += "+" ;work2Article1.innerText=`${num}`;}work2BtnNull.onclick = function () {alert('下次⼀定开发出来');}work2BtnPoi.onclick = function () { num += "." ;work2Article1.innerText=`${num}`; }work2BtnSub.onclick = function () { num += "-" ;work2Article1.innerText=`${num}`; }// 数字点击事件work2Btn1.onclick =function(){if( num == "0" ){num = "1";}else{num += "1" ;}work2Article1.innerText=`${num}`; }work2Btn2.onclick =function(){if( num == "0" ){num = "2";}else{num += "2" ;}work2Article1.innerText=`${num}`; }work2Btn3.onclick =function(){if( num == "0" ){num = "3";}else{num += "3" ;}work2Article1.innerText=`${num}`; }work2Btn4.onclick =function(){if( num == "0" ){num = "4";}else{num += "4" ;}work2Article1.innerText=`${num}`; }work2Btn5.onclick =function(){if( num == "0" ){num = "5";}else{num += "5" ;}work2Article1.innerText=`${num}`; }work2Btn6.onclick =function(){if( num == "0" ){num = "6";}else{num += "6" ;}work2Article1.innerText=`${num}`; }work2Btn7.onclick =function(){if( num == "0" ){num = "7";}else{num += "7" ;}work2Article1.innerText=`${num}`; }work2Btn8.onclick =function(){if( num == "0" ){num = "8";}else{num += "8" ;}work2Article1.innerText=`${num}`; }work2Btn9.onclick =function(){if( num == "0" ){num = "9";}else{num += "9" ;}work2Article1.innerText=`${num}`;}work2Btn0.onclick =function(){if( num == "0" ){num = "0";}else{num += "0" ;}work2Article1.innerText=`${num}`;}work2BtnEqu.onclick = function () {// num = Number(num);//检测运算符号的位置function obtainSymbol(){var num1 = [];var o = 0 ;for(var i = 0 ; i<=num.length ; i++){if(num.charAt(i)=='+'){num1[o] = i ;o++;}else if(num.charAt(i)=='-'){num1[o] = i ;o++;}else if(num.charAt(i)=='*'){num1[o] = i ;o++;}else if(num.charAt(i)=='/'){num1[o] = i ;o++;}else if(num.charAt(i)=='%'){num1[o] = i ;o++;}}return num1 ;}var res1 = 0 ; //计算结果var numStar = num ; //重新获取原式⼦// 检测乘除取余运算var num1 = obtainSymbol();console.log(num1);// 检测除了第⼀个符号之外的乘除取余运算for( var w = 0 ; w <= num1.length ; w++ ){if(w != 0){if( num.charAt(num1[w]) == '*' || num.charAt(num1[w]) == '/' || num.charAt(num1[w]) == '%' ){if(w != num1.length-1){switch(num.charAt(num1[w])){case '*': var l =Number(num.substring(num1[w-1],num1[w]))*Number(num.substring(num1[w]+1,num1[w+1])) ; console.log(l);num = num.substring(0,num1[w-1]+1) + l + num.substring(num1[w+1]) ;break;case '/': var l =Number(num.substring(num1[w-1],num1[w]))*Number(num.substring(num1[w]+1,num1[w+1])) ; num = num.substring(0,num1[w-1]+1) + l + num.substring(num1[w+1]) ; break;case '%': var l =Number(num.substring(num1[w-1],num1[w]))*Number(num.substring(num1[w]+1,num1[w+1])) ; num = num.substring(0,num1[w-1]+1) + l + num.substring(num1[w+1]) ; break;}}else if(w == num1.length-1 ){switch(num.charAt(num1[w])){case '*': var l =Number(num.substring(num1[w-1]+1,num1[w])) * Number(num.substring(num1[w]+1)) ;num = num.substring(0,num1[w-1]+1) + l ;break;case '/': var l =Number(num.substring(num1[w-1]+1,num1[w])) / Number(num.substring(num1[w]+1)) ;num = num.substring(0,num1[w-1]+1) + l ; break;case '%': var l =Number(num.substring(num1[w-1]+1,num1[w])) % Number(num.substring(num1[w]+1)) ;num = num.substring(0,num1[w-1]+1) + l; break;}}num1 = 0 ;num1 = obtainSymbol();w -= 1;}}}// 从第⼀位运算符开始运算for(var k = 0 ; k < num1.length ; k++){if(k==0){switch(num.charAt(num1[k])){case '+': res1 += Number(num.substring(0,num1[k])) + Number(num.substring(num1[k]+1,num1[k+1])) ; break; case '-': res1 += Number(num.substring(0,num1[k])) - Number(num.substring(num1[k]+1,num1[k+1])) ; break;case '*': res1 += Number(num.substring(0,num1[k])) * Number(num.substring(num1[k]+1,num1[k+1])) ; break; case '/': res1 += Number(num.substring(0,num1[k])) / Number(num.substring(num1[k]+1,num1[k+1])) ; break;case '%': res1 += Number(num.substring(0,num1[k])) % Number(num.substring(num1[k]+1,num1[k+1])) ; break; }}else{switch(num.charAt(num1[k])){case '+':if(k==num1.length-1){res1 += Number(num.substring(num1[k]+1)) ;}else{res1 += Number(num.substring(num1[k]+1,num1[k+1]));}break;case '-':if(k==num1.length-1){res1 -= Number(num.substring(num1[k]+1)) ;}else{res1 -= Number(num.substring(num1[k]+1,num1[k+1]));}break;case '*':if(k==num1.length-1){res1 *= Number(num.substring(num1[k]+1)) ;}else{res1 *= Number(num.substring(num1[k]+1,num1[k+1]));}break;case '/':if(k==num1.length-1){res1 /= Number(num.substring(num1[k]+1)) ;}else{res1 /= Number(num.substring(num1[k]+1,num1[k+1]));}break;case '%':if(k==num1.length-1){res1 %= Number(num.substring(num1[k]+1)) ;}else{res1 %= Number(num.substring(num1[k]+1,num1[k+1]));}break;}}}work2Article1.innerText=`${numStar}=${res1}`;}</script></body></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
JavaScript实现简单的计算器功能
JavaScript实现简单的计算器功能本⽂实例为⼤家分享了JavaScript实现简单计算器功能的具体代码,供⼤家参考,具体内容如下具体要求如下:实现代码:<html><head><meta charset="utf-8"><title>计算器</title><script>function myck(type){var num1 = document.getElementById("num1");var num2 = document.getElementById("num2");if(type==1){// 计算操作var result = parseInt(num1.value) + parseInt(num2.value);alert(result);document.getElementById("resultDiv").innerText ="最终计算结果:"+ result;}else if(type==2){var result = parseInt(num1.value) - parseInt(num2.value);alert(result);document.getElementById("resultDiv").innerText ="最终计算结果:"+ result;}else if(type==3){var result = parseInt(num1.value) * parseInt(num2.value);alert(result);document.getElementById("resultDiv").innerText ="最终计算结果:"+ result;}else if(type==4){if(confirm("是否正确清空?")){// 清空num1.value = "";num2.value = "";document.getElementById("resultDiv").innerText="";}}}</script></head><body><div style="margin-top: 100px;margin-left: 500px;"><span style="font-size: 60px;">计算器</span></div><div><div class="innerDiv" style="margin-left: 490px;">数 字1:<input id="num1" type="number" placeholder="请输⼊数字1"></div></div><div><div class="innerDiv" style="margin-left:490px;">数 字2:<input id="num2" type="number" placeholder="请输⼊数字2"></div></div><div><div style="margin-left: 500px;" class="innerDiv"><input type="button" onclick="myck(1)" value="相 加"><input type="button" onclick="myck(2)" value="相 减"><input type="button" onclick="myck(3)" value="相 乘"><input type="button" onclick="myck(4)" value="清 空"></div></div><div id="resultDiv"></div></body><style>.innerDiv{margin-left: 420px;margin-top: 20px;}</style></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
js+html实现简易网页计算器
js+html实现简易⽹页计算器前⾔很早之前就想⽤js写⼀个简单的计算器,今天这个⼼愿算是完成了,作为⽤js做的第⼀个⼩项⽬,挣扎了⼀下午,代码其实挺简单的,⽆奈本⼈太菜了,代码⼗分钟,bug半⼩时;图⽚展⽰其实第⼀张图才是我想做的计算器,但是最上⾯⼀⾏的功能⽆法实现,并且第⼀张是⽤grid布局写的,添加js不⽅便,于是我⼜写了第⼆张图的界⾯这个计算器的主要特点就是可以在屏幕上显⽰出⽤户想要计算的整个表达式,然后直接计算出结果,⽽不需要每进⾏⼀次加减乘除的运算都要按等于号;功能与界⾯是仿照的vivo⼿机⾃带的计算器,由于我⽤的就是vivo⼿机;html 部分1、第⼀张图⽚<div class="container"><input type="button" id="screen"><input type="button" id="mc" value="mc"><div id="m1"> m+</div><div id="m-"> m-</div><div id="mr"> mr</div><div id="ac">AC </div><div id="delete"><-</div><div id="bracket"> +/-</div><div id="chu"> ÷</div><div id="num7">7</div><div id="num8">8</div><div id="num9">9</div><div id="num4">4</div><div id="num5">5</div><div id="num6">6</div><div id="num1">1</div><div id="num2">2</div><div id="num3">3</div><div id="cheng">×</div><div id="num0">0</div><div id="spot">.</div><div id="add">+</div><div id="minus">-</div><div id="equal">=</div></div>2、第⼆张图⽚<body><table><tr><td colspan="4"><input class="screen" type="text" disabled /></td></tr><tr><td><input class="but_ac but" type="button" value="AC" style="color: orange"></td><td><input class="but_ac but" type="button" value="<—" style="color: orange"></td><td><input class="but" type="button" value="+/-"></td><td><input class="but" type="button" value="/"></td></tr><tr><td><input class="but" type="button" value="7"></td><td><input class="but" type="button" value="8"></td><td><input class="but" type="button" value="9"></td><td><input class="but" type="button" value="*"></td></tr><tr><td><input class="but" type="button" value="4"></td><td><input class="but" type="button" value="5"></td><td><input class="but" type="button" value="6"></td><td><input class="but" type="button" value="-"></td></tr><tr><td><input class="but" type="button" value="1"></td><td><input class="but" type="button" value="2"></td><td><input class="but" type="button" value="3"></td><td><input class="but" type="button" value="+"></td></tr><tr><td colspan="2"><input class="but" type="button" value="0" style="width: 180px"></td><td><input class="but" type="button" value="."></td><td><input class="but" type="button" value="=" style="background-color:orange ;color:white"></td></tr></table></body>html部分就是简单的⽤table写的,在单元格内嵌套按钮,为了和⼿机上的界⾯更像,AC、<-、=这三个按钮单独设置了字体颜⾊和背景颜⾊;eval函数在计算表达式的时候,只能识别乘号和除号只能识别*和/,⽽不是数学上的×和÷,因此,按钮修改了⼀下,下⾯的代码在⽹页打开之后,和上⾯的图⽚两个按钮有所不同;css部分第⼀张图⽚的.container{display: grid;width: 350px;height: 550px;grid-template-columns:repeat(4,25%); grid-template-rows:repeat(8,12.5%); background-color:lightgray;margin-top: 50px;text-align: center;line-height: 68.75px;font-size: 1.5em;}#screen{grid-column: 1/5;grid-row: 1/3;background-color: black;}#mc{grid-column: 1/2;grid-row: 3/4;border:solid 1px gray;border-left: 0px;font-size: 1.1em;background-color:lightgray;}#m1{grid-column: 2/3;grid-row: 3/4;border:solid 1px gray;border-left: 0px;}#m-{grid-column:3/4;grid-row: 3/4;border:solid 1px gray;border-left: 0px;}#mr{grid-column: 4/5;grid-row: 3/4;border:solid 1px gray;border-right: 0px;border-left: 0px;}#ac{grid-column:1/2;grid-row: 4/5;border:solid 1px gray;border-left: 0px;color: orange;border-top: 0px;}#delete{grid-column:2/3;grid-row: 4/5;border:solid 1px gray;border-left: 0px;color: orange;border-top: 0px;}#bracket{grid-column:3/4;grid-row: 4/5;border:solid 1px gray;border-left: 0px;border-top: 0px;}#chu{grid-column:4/5;grid-row: 4/5;border:solid 1px gray;border-left: 0px;border-top: 0px;border-right: 0px;}#num7{grid-column:1/2;grid-row: 5/6;border:solid 1px gray;border-left: 0px;}#num8{grid-column:2/3;grid-row: 5/6;border:solid 1px gray; border-left: 0px;border-top: 0px;}#num9{grid-column:3/4;grid-row: 5/6;border:solid 1px gray; border-left: 0px;border-top: 0px;}#cheng{grid-column:4/5;grid-row: 5/6;border:solid 1px gray; border-left: 0px;border-top: 0px;border-right: 0px;}#num4{grid-column:1/2;grid-row: 6/7;border:solid 1px gray; border-left: 0px;border-top: 0px;}#num5{grid-column:2/3;grid-row: 6/7;border:solid 1px gray; border-left: 0px;border-top: 0px;}#num6{grid-column:3/4;grid-row: 6/7;border:solid 1px gray; border-left: 0px;border-top: 0px;}#minus{grid-column:4/5;grid-row: 6/7;border:solid 1px gray; border-left: 0px;border-top: 0px;border-right: 0px;}#num1{grid-column:1/2;grid-row: 7/8;border:solid 1px gray; border-left: 0px;border-top: 0px;}#num2{grid-column:2/3;grid-row: 7/8;border:solid 1px gray; border-left: 0px;border-top: 0px;}#num3{grid-column:3/4;grid-row: 7/8;border:solid 1px gray; border-left: 0px;border-top: 0px;}#add{grid-column:4/5;grid-row: 7/8;border:solid 1px gray; border-left: 0px;border-top: 0px;border-right: 0px;}#num0{grid-row: 8/9;border:solid 1px gray;border-left: 0px;border-top: 0px;}#spot{ grid-column:3/4;grid-row: 8/9;border:solid 1px gray;border-left: 0px;border-top: 0px;}#equal{grid-column:4/5;grid-row: 8/9;border:solid 1px gray;border-left: 0px;border-top: 0px;border-right: 0px;color: white;background-color: orange;}第⼆张图⽚的<style type="text/css">table{margin:0 auto; //使整个计算器的界⾯位于⽹页中央}.but_ac{width: 80px;height: 60px;background-color : lightgray; //设置按钮的背景颜⾊为浅灰⾊font-size: 1.2em; //设置字体⼤⼩}.but{width: 80px;height: 60px;background-color : lightgray;font-size: 1.2em;}.screen{width: 350px;height: 70px;font-size: 1.5em;color: white;background-color: black;text-align:right; //使⽤户输⼊的表达数从屏幕的右边开始显⽰}</style>js部分思路获取⽤户所点击的按钮上的元素将获取的元素显⽰在屏幕上调⽤eval函数计算表达式的结果整体就是⽤⼀连串的if else语句判断你所点击的按钮,然后作出回应代码<script type="text/javascript">window.onload=function(){var num=document.getElementsByClassName("but"); //num数组存放元素对象var scr=document.getElementsByClassName("screen")[0]; //获取屏幕对象for(var i=0;i<num.length;i++) //通过for循环为每个按钮添加onclick事件{num[i].onclick=function(){if(this.value=="AC"){ //如果点击AC,则清空屏幕scr.value="";}else if( this.value=="+/-"){ //如果点击“+/-”按钮有两种情况//第⼀种情况,如果此时屏幕为空,则什么也不显⽰if(scr.value==""){scr.value="";}//如果屏幕不为空,就判断最后两个元素是不是运算符加数字的结构else if(isNaN(scr.value.charAt(scr.value.length- 1))==false&&isNaN(scr.value.charAt(scr.value.length-2))==true) {//给最后⼀个数字加括号并变为负数}}//当屏幕不为空时,判断点击的是不是退格键else if (this.value=="<—"&&this.value!=""){//将最后⼀个元素截掉scr.value=scr.value.substr(0,scr.value.length-1);}//当屏幕为空时判断是否点击的是⼩数点else if(scr.value==""&&this.value=="."){scr.value="0.";}//当点击等于号时,⽤eval函数计算表达式的结果并显⽰到屏幕上else if(this.value=="="){scr.value=eval(scr.value);}//当屏幕为空时,点击+、-、*、/时不做反应else if(scr.value==""&&(this.value=="+"||this.value=="-"||this.value=="*"||this.value=="/")) {scr.value=="";}else{scr.value+=this.value;}}}}</script>完整代码<!DOCTYPE html><html><head><title>jsss</title><style type="text/css">table{margin:0 auto;}.but_ac{width: 80px;height: 60px;background-color : lightgray;font-size: 1.2em;}.but{width: 80px;height: 60px;background-color : lightgray;font-size: 1.2em;}.screen{width: 350px;height: 70px;font-size: 1.5em;color: white;background-color: black;text-align:right;}</style><script type="text/javascript">window.onload=function(){var result;var str=[];var num=document.getElementsByClassName("but");var scr=document.getElementsByClassName("screen")[0];for(var i=0;i<num.length;i++){num[i].onclick=function(){if(this.value=="AC"){scr.value="";}else if( this.value=="+/-"){if(scr.value==""){scr.value="";else if(isNaN(scr.value.charAt(scr.value.length-1))==false&&isNaN(scr.value.charAt(scr.value.length-2))==true) {scr.value=scr.value.substr(0,scr.value.length-1)+"("+"-"+scr.value.charAt(scr.value.length-1)+")";}}else if (this.value=="<—"&&this.value!=""){scr.value=scr.value.substr(0,scr.value.length-1);}else if(scr.value==""&&this.value=="."){scr.value="0.";}else if(this.value=="="){scr.value=eval(scr.value);}else if(scr.value==""&&(this.value=="+"||this.value=="-"||this.value=="*"||this.value=="/")){scr.value=="";}else{scr.value+=this.value;}}}}</script></head><body><table><tr><td colspan="4"><input class="screen" type="text" disabled /></td></tr><tr><td><input class="but_ac but" type="button" value="AC" style="color: orange"></td><td><input class="but_ac but" type="button" value="<—" style="color: orange"></td><td><input class="but" type="button" value="+/-"></td><td><input class="but" type="button" value="/"></td></tr><tr><td><input class="but" type="button" value="7"></td><td><input class="but" type="button" value="8"></td><td><input class="but" type="button" value="9"></td><td><input class="but" type="button" value="*"></td></tr><tr><td><input class="but" type="button" value="4"></td><td><input class="but" type="button" value="5"></td><td><input class="but" type="button" value="6"></td><td><input class="but" type="button" value="-"></td></tr><tr><td><input class="but" type="button" value="1"></td><td><input class="but" type="button" value="2"></td><td><input class="but" type="button" value="3"></td><td><input class="but" type="button" value="+"></td></tr><tr><td colspan="2"><input class="but" type="button" value="0" style="width: 180px"></td><td><input class="but" type="button" value="."></td><td><input class="but" type="button" value="=" style="background-color:orange ;color:white"></td></tr></table></body></html>。
JavaScript实现计算器的四则运算功能
JavaScript实现计算器的四则运算功能⽬录⼀、需求 + 最终实现1. 需求2. 说明:利⽤了字符串(split、replace)和数组(splice)的⽅法。
3. 代码实现⼆、实现步骤1. 版本⼀:实现基础加减乘除2. 版本⼆:实现⾼位数的运算3. ⽀持多次的运算三、思考后端思维前端思维结束⼀、需求 + 最终实现注:只是前端实现1. 需求需求来源是因为有⼀个做嵌⼊式 C/C++的基友做了⼀个远程计算器。
需求是要求⽀持输⼊⼀个四则混合运算公式的字符串,返回计算后的结果。
想看看⽤ C/C++封装过的 JavaScript 如果要实现这样⼀个功能最终效果(⽂章后我会讨论这两种实现思路,还望各位看官可以提出⼀些优化⽅案以及建议之类的~)。
2. 说明:利⽤了字符串(split、replace)和数组(splice)的⽅法。
主要是⽤到字符串切分为数组的⽅法 split、以及数组中插⼊删除的⽅法 splice。
字符串正则 replace ⽅法是考虑到⽤户的输⼊习惯可能有所不同,例如 1+2*3/4与 3 * 7 + 229。
⽀持:基础四则运算 3+6*5/6-3;⼩数四则运算 3.14 + 6 * 5 / 6 - 3.5;⾼位四则运算 99 * 94 - 6.35 + 100 / 1024;多次四则运算 3 * 3 + 3 * 16 - 7 - 5 + 4 / 2 + 22;以上综合不⽀持:带括号的运算 1 * (2 - 3);其他数学运算3. 代码实现/*** js四则混合运算计算器功能实现(约20⾏+ ⾯条代码)* @param {string} str 输⼊的四则运算字符串* @return {number} 输出结果*/const calculator = (str) => {// 定义添加字符函数const add = (arr, symbol) => {let length = arr.length;while (length > 1) {arr.splice(length - 1, 0, symbol); // 在每⼀项后⾯添加对应的运算符length--;}return arr; // ⽬的是得到⼀个改变长度的数组}const array = add(str.replace(/\s*/g,"").split('+'), '+').map(it => add(it.split('-'), '-').map(it => add(it.split('*'), '*').map(it => add(it.split('/'), '/')))).flat(3);;// 先运算乘除法['*', '/'].map(it => {while (array.includes(it)) {const index = array.findIndex(o => o === it);index > 0 && it === '*' ? array.splice(index - 1, 3, (Number(array[index - 1]) * Number(array[index + 1]))) : array.splice(index - 1, 3, (Number(array[index - 1]) / Number(array[index + 1])));}})// 再执⾏加减法,即从左⾄右的计算while (array.length > 1) {array[1] === '+' ? array.splice(0, 3, (Number(array[0]) + Number(array[2]))) : array.splice(0, 3, (Number(array[0]) - Number(array[2])));}return Number(array[0]).toFixed(2);}如果对 ES6 语法还算熟悉的话,应该可以轻松阅读代码的。
用JavaScript写一个简单的计算器
⽤JavaScript写⼀个简单的计算器本⽂使⽤js实现了⼀个简单的加、减、乘、除计算器。
以下是css部分代码:*{padding:0;margin:0;color: #424242;}.outer{width:300px;height:auto;outline:1px solid #b9b9b9;margin:50px auto;background: pink;}.title{height:40px;width:100%;border-bottom:1px solid #b9b9b9;text-align: left;text-indent:10px;line-height: 40px;cursor: pointer;}.bodyBox{width:90%;height:auto;padding:5%;}.calView{width:100%;height:75px;outline:1px solid #b9b9b9;background: rgba(255,255,255,.8);overflow: scroll;text-indent: 5px;padding-top:5px;}.content,.contentBtn{display: flex;justify-content: space-between;align-items: center;flex-wrap: wrap;}.btn,.back,.reset{display: inline;width:22%;height:30px;margin-top:15px;text-align: center;line-height:30px;cursor: pointer;background: #ffe4e8;outline:none;border:3px solid #ffa2a5;border-left:none;border-top:none;}.back,.reset{width:47%;}以下是html部分代码:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>计算器</title><link rel="stylesheet" href="calculator.css"></head><body><div class="outer"><div class="title"><span>计算器</span></div><div class="bodyBox"><div class="calView"></div><div class="content"><button class="btn">7</button><button class="btn">8</button><button class="btn">9</button><button class="btn">+</button><button class="btn">4</button><button class="btn">5</button><button class="btn">6</button><button class="btn">-</button><button class="btn">1</button><button class="btn">2</button><button class="btn">3</button><button class="btn">*</button><button class="btn">0</button><button class="btn">.</button><button class="btn">=</button><button class="btn">/</button></div><div class="contentBtn"><button class="back">回退</button><button class="reset">清空</button></div></div></div><script src="calculator.js"></script></body></html>以下是js部分代码(使⽤了es6的语法,使⽤之前请将编辑器设置为⽀持es6语法):/*** Created by Administrator on 2018/10/1.*/(function(){let content=document.getElementsByClassName("content")[0];let calView=document.getElementsByClassName("calView")[0];let reset=document.getElementsByClassName("reset")[0];//清空按钮let back=document.getElementsByClassName("back")[0];//回退按钮let arr=[];//存放输⼊的内容content.onmousedown=function(event){e=window.event||arguments[0];let tar=e.target||e.srcElement;tar.style.boxShadow="-1px -1px 3px #ffa2a5 inset";//设置按钮点击内阴影样式content.onmouseup=function(event){tar.style.boxShadow="none";};let val=tar.innerText;if(calView.innerHTML.indexOf("=")!==-1){//如果已经计算出结果,则开始下⼀次计算,清空数组calView.innerHTML="";arr=[];}calView.innerHTML="";arr.push(val);//将输⼊内容放⼊数组if(!isNaN(parseFloat(val))){//如果输⼊数字,则进⾏拼接joinNum(val);}if(isNaN(parseFloat(arr[arr.length-2])) && isNaN(parseFloat(arr[arr.length-1]))){//如果上⼀位和这⼀位为符号,则删除这⼀位 arr.pop();}show();//更新窗⼝内容if(val==="=" && arr.length>1){//如果输⼊等号,则计算出结果compute(arr);}};reset.onclick=()=>{//清空输⼊的内容calView.innerHTML="";arr=[];//清空数组};back.onclick=()=>{//清空输⼊的内容arr.pop();show();};/*** 拼接输⼊的内容* @param val :⽤户输⼊的内容*/function joinNum(val){if(!isNaN(parseFloat(arr[arr.length-2]))){//检测上⼀个是否为数字arr[arr.length-2]=String(parseFloat(arr[arr.length-2])*10+parseFloat(val));arr.pop();}if(arr[arr.length-2] === "/" && arr[arr.length-1] ==="0"){//如果分母为0,则删除0arr.pop();}}/*** 更新显⽰窗⼝内容*/function show(){let arrLen=arr.length;let str="";for(let i=0;i<arrLen;i++){str+=arr[i];}calView.innerHTML=str;//将拼接好的字符串显⽰在结果窗⼝中return str;}/*** 计算出最终结果*/function compute(arr){let showStr=show();calView.innerHTML=showStr + eval(showStr.split("=")[0]).toFixed(6);//由于会出现精度丢失问题,因此这⾥⽤toFixed()处理⼀下 }})();最终效果如下图所⽰,样式我写得⽐较随意,将就看吧!(本⽂为原创,转载请注明,谢谢!如果发现bug,请⼤家提出来!)。
基于html+css+js实现简易计算器代码实例
基于html+css+js实现简易计算器代码实例使⽤html+css+js实现简易计算器,效果图如下:html代码如下<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>calculator</title><link rel="stylesheet" type="text/css" href="style.css" rel="external nofollow" ><script type="text/javascript" src="contain.js"></script><title>Document</title></head><body><div class="calculator"><form name="calculator"><input type="text" id="display" value=""><br><input type="button" class="btn number txt" value="TYNAM"><input type="button" id="clear" class="btn number" value="AC" onclick="cleardisplay();"><input type="button" class="btn number" value="<-" onclick="del();"><input type="button" class="btn operator" value="/" onclick="get(this.value);"><br><input type="button" class="btn number" value="7" onclick="get(this.value);"><input type="button" class="btn number" value="8" onclick="get(this.value);"><input type="button" class="btn number" value="9" onclick="get(this.value);"><input type="button" class="btn operator" value="*" onclick="get(this.value);"><br><input type="button" class="btn number" value="4" onclick="get(this.value);"><input type="button" class="btn number" value="5" onclick="get(this.value);"><input type="button" class="btn number" value="6" onclick="get(this.value);"><input type="button" class="btn operator" value="+" onclick="get(this.value);"><br><input type="button" class="btn number" value="1" onclick="get(this.value);"><input type="button" class="btn number" value="2" onclick="get(this.value);"><input type="button" class="btn number" value="3" onclick="get(this.value);"><input type="button" class="btn operator" value="-" onclick="get(this.value);"><br><input type="button" class="btn number" value="0" onclick="get(this.value);"><input type="button" class="btn number" value="." onclick="get(this.value);"><input type="button" class="btn operator equal" value="=" onclick="calculates();"></form></div></body></html>CSS代码如下:border: none;font-family: 'Open Sans', sans-serif;margin: 0;padding: 0;}.calculator {background-color: #fff;height: 600px;margin: 50px auto;width: 600px;}form {background-color: rgb(75, 70, 71);padding: 5px 1px auto;width: 245px;}.btn {outline: none;cursor: pointer;font-size: 20px;height: 45px;margin: 5px 0 5px 10px;width: 45px;}.btn:first-child {margin: 5px 0 5px 10px;}#display {outline: none;background-color: #dededc;color: rgb(75, 70, 71);font-size: 40px;height: 47px;text-align: right;width: 224px;margin: 10px 10px auto;}.number {background-color: rgb(143, 140, 140);color: #dededc;}.operator {background-color: rgb(239, 141, 49);color: #ffffff;}.equal{width: 105px;}.txt{font-size:12px;background: none;}JS代码如下:/* display clear */function cleardisplay() {document.getElementById("display").value = "";}/* del */function del() {var numb = "";numb = document.getElementById("display").value;for(i=0;i<numb.length;i++){document.getElementById("display").value = numb.substring(0,numb.length-1); if(numb == '')document.getElementById("display").value = '';}}}/* recebe os valores */function get(value) {document.getElementById("display").value += value;}/* calcula */function calculates() {var result = 0;result = document.getElementById("display").value;document.getElementById("display").value = "";document.getElementById("display").value = eval(result);};以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
HTML5+css+JavaScript进行四则运算简易计算器(用Grid网格实现)
HTML5+JavaScript:<!DOCTYPE html><html><head><meta charset="utf-8" /><title></title><link rel="stylesheet" type="text/css" href="css/style.css" /></head><body><form><input id="textid" type="text" style="width: 350px; height: 40px; background-color: antiquewhite; margin: 10px; font-size: 30px;" placeholder="Grid列表简易计算器"/></form><div class="container"><div class="item-1" onclick="empty()" value="C">C</div><div class="item-2" onclick="addStr('/')">÷</div><div class="item-3" onclick="addStr('*')">X</div><div class="item-4" onclick="del()">退格</div><div class="item-5" onclick="addStr(7)">7</div><div class="item-6" onclick="addStr(8)">8</div><div class="item-7" onclick="addStr(9)">9</div><div class="item-8" onclick="addStr('-')">-</div><div class="item-9" onclick="addStr(4)">4</div><div class="item-10" onclick="addStr(5)">5</div><div class="item-11" onclick="addStr(6)">6</div><div class="item-12" onclick="addStr('+')">+</div><div class="item-13" onclick="addStr(1)">1</div><div class="item-14" onclick="addStr(2)">2</div><div class="item-15" onclick="addStr(3)">3</div><div class="item-16" onclick="calculates()">=</div><div class="item-17" onclick="percent()">%</div><div class="item-18" onclick="addStr(0)">0</div><div class="item-19" onclick="addStr('.')">.</div></div><script>var inputvalue = document.getElementById("textid");function addStr(x){inputvalue.value = inputvalue.value + x;}function calculates(){inputvalue.value = eval(inputvalue.value);}function empty(){inputvalue.value = null;}function del(){inputvalue.value = inputvalue.value.substr(0,inputvalue.value.length-1);}function percent(){inputvalue.value = inputvalue.value/100;}</script></body></html>Css:.container {display: grid;width: 320px;height: 320px;margin: 10px;grid-template-columns: 80px 80px 80px 80px;grid-template-rows: 80pxpx 80px 80px;column-gap: 10px;row-gap: 10px;grid-template-areas:"a b c d""e f g h""i j k l""m n o p""q r s p";}.item-1{grid-area: a;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-2{grid-area: b;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-3{grid-area: c;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-4{grid-area: d;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-5{grid-area: e;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-6{grid-area: f;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-7{grid-area: g;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-8{grid-area: h;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-9{grid-area: i;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-10{grid-area: j;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-11{grid-area: k;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-12{grid-area: l;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-13{grid-area: m;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-14{grid-area: n;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-15{grid-area: o;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-16{grid-area: p;background-color: aquamarine;font-size:30px;text-align: center;line-height: 100px;cursor: pointer;}.item-17{grid-area: q;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-18{grid-area: r;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}.item-19{grid-area: s;background-color: aquamarine;font-size:30px;text-align: center;line-height: 50px;cursor: pointer;}。
JS制作简易计算器的实例代码
JS制作简易计算器的实例代码做⼀个简易计算器,效果图⽚c表⽰清空,为⼀个空字符串+/-表⽰该值为正还是负%表⽰当前值/100←表⽰退格,往前删除⼀个值eval 函数是能够计算出字符串表达式或者语句的结果,把结果求出来。
代码如下<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">#div1{margin:20px auto;width:420px;height:490px;background-color:#E8E8E8;border:1px solid #ccc;border-radius:5px;}.div2{width:410px;height:60px;border:1px solid #ccc;margin:5px auto;border-radius:5px;text-align:right;font-size:30px;background-color:white;padding-top:10px;}.div3{width:410px;height:60px;margin:5px auto;float:left;}.div13{float:left;width:70px;height:60px;border:1px solid #ccc;background-color: ghostwhite;margin-left:8px;text-align:center;font-size:30px;color:deepskyblue;border-radius:5px;cursor:default;padding-top:10px;box-shadow:4px 3px 3px #CCCCCC;}.div133{width:160px;}.top{margin-top:10px;margin-left:10px;}.color{color:black;}.top1{margin-top:20px;margin-left:10px;}.top2{margin-top:30px;margin-left:10px;}.top3{margin-top:40px ;margin-left:10px;}.div23{float:left;}.div33{float:left;}</style><div id="div1"><div class="div2" id="input"><b>0</b></div><div class="div3"><div class="div13" onclick="w(' ')"><b>C</b></div><div class="div13"onclick="w('opposite')"><b>+/-</b></div><div class="div13" onclick="w('percent')"><b>%</b></div><div class="div13 div133" onclick="w('backspace')"><b>←</b></div></div><div class="div3"><div class="div13 top color" onclick="a('7')"><b>7</b></div><div class="div13 top color" onclick="a('8')"><b>8</b></div><div class="div13 top color" onclick="a('9')"><b>9</b></div><div class="div13 top " onclick="a('+')"><b>+</b></div><div class="div13 top " onclick="a('-')"><b>-</b></div></div><div class="div3"><div class="div13 top1 color" onclick="a('4')"><b>4</b></div><div class="div13 top1 color"onclick="a('5')"><b>5</b></div><div class="div13 top1 color" onclick="a('6')"><b>6</b></div><div class="div13 top1" onclick="a('*')"><b>×</b></div><div class="div13 top1" onclick="a('/')"><b>÷</b></div></div><div class="div3"><div class="div13 top2 color" onclick="a('1')"><b>1</b></div><div class="div13 top2 color" onclick="a('2')"><b>2</b></div><div class="div13 top2 color"onclick="a('3')"><b>3</b></div><div class="div13 top2"onclick="w('pow')"><b>x<sup>2</sup></b></div><div class="div13 top2" onclick="w('sqrt')"><b>√</b></div></div><div class="div3"><div class="div13 top3 color" onclick="a('0')"><b>0</b></div><div class="div13 top3"onclick="a('.')"><b>.</b></div><div class="div13 top3"onclick="e('=')"><b>=</b></div></div></div><script>input=document.getElementById("input");s="";function a(v){s=s+v;input.innerHTML=s;}function e(v){input.innerHTML=eval(s);}function w(type){switch(type){ case ' ':s='';break;case 'opposite':s=-s;break;case 'percent':s=s/100;break;case 'pow':s=Math.pow(s,2);break;case 'sqrt':s=Math.sqrt(s);break;case 'backspace':s=s.substr(s,s.length-1);// case 'backspace':s=s.substring(0,s.length-1); }input.innerHTML=s;}</script>这⾥我本来是采⽤的substring这个函数的,但是在计算的时候,当只留下⼀个值的时候,按←的时候就不起作⽤,但是把substring改成substr的时候就能清除的了,原因我觉得应该是这样:s=s.substring(s,s.length-1);当只剩下⼀个值的时候,假设s 值为7,substring中的第⼀个参数为是,表⽰中国字符串的⾸地址,就是0,第⼆个参数为0,怎么取,但是换成这样是可以的s=s.substring(0,s.length-1);,但是⽤s=s.substr(s,s.length-1);当只剩下⼀个值的时候是可以清除掉的,我想应该是当第⼆个参数是取得个数为0的时候,就把空字符串赋给s了吧。
JS实现的加减乘除四则运算计算器示例
JS实现的加减乘除四则运算计算器⽰例本⽂实例讲述了JS实现超级简易的加减乘除四则运算计算器。
分享给⼤家供⼤家参考,具体如下:先来看看运⾏效果:具体代码如下:<!DOCTYPE html><html><head><meta charset="UTF-8"><title>简单的计算器()</title><style>body{margin: 0;}.tab{border: 3px solid black ;border-radius: 2px;border-collapse:collapse;width: 268px;height: 402px;margin: 20px auto;}.tr{height: 67px;width: 268px;border: 3px solid black ;text-align: right;}.tr1{width: 268px;height: 67px;border: 3px solid black ;text-align: center;}.tr2{width: 67px;height: 67px;border: 3px solid black ;text-align: center;}</style><script>var s1 = "";var s2 = "";var s3 = "";var s4 = "";var s5 = "";function view(val){var a = document.getElementById(val);s1 = a.innerHTML;if(s1=="+" || s1=="-" || s1=="*" || s1=="/"){s3 = s1;s1 = "";}if(s3=="+" || s3=="-" || s3=="*" || s3=="/"){add2(s1);}if(s3==""){add1(s1);}}function add1(s1){s2 = s2 + s1;show();}function add2(s1){s4 = s4 + s1;show();}function cal(){switch(s3){case "+":{s5 = (String)((parseFloat(s2)+parseFloat(s4)).toFixed(2));result.innerHTML = s5;break;}case "-":{s5 = (String)((parseFloat(s2)-parseFloat(s4)).toFixed(2));result.innerHTML = s5;break;}case "*":{s5 = (String)((parseFloat(s2)*parseFloat(s4)).toFixed(2));result.innerHTML = s5;break;}case "/":{s5 = (String)((parseFloat(s2)/parseFloat(s4)).toFixed(2));result.innerHTML = s5;break;}}}function show(){var result = document.getElementById("result");result.innerHTML = s2+s3+s4;}</script></head><body><table class="tab"><tr class = "tr2"><td colspan="4">简易计算器</td></tr><tr class="tr"><td id="result" colspan="4" ></td></tr><tr ><td id="+" class="tr1" onclick="view('+')">+</td><td id="-" class="tr1" onclick="view('-')">-</td><td id="*" class="tr1" onclick="view('*')">*</td><td id="/" class="tr1" onclick="view('/')">/</td></tr><tr ><td id="7" class="tr1" onclick="view('7')">7</td><td id="8" class="tr1" onclick="view('8')">8</td><td id="9" class="tr1" onclick="view('9')">9</td><td id="0" class="tr1" onclick="view('0')">0</td></tr><tr><td id="4" class="tr1" onclick="view('4')">4</td><td id="5" class="tr1" onclick="view('5')">5</td><td id="6" class="tr1" onclick="view('6')">6</td><td id="." class="tr1" onclick="view('.')">.</td></tr><tr><td id="1" class="tr1" onclick="view('1')">1</td><td id="2" class="tr1" onclick="view('2')">2</td><td id="3" class="tr1" onclick="view('3')">3</td><td id="=" class="tr1" onclick="cal()" >=</td></tr></table></body></html>对于这个程序来说,判断的顺序⾮常重要,不然就会把"+"号存在s2,s4中⽽不是s3中。
JavaScript四则运算计算器
8
<br>
9
<button id="add">+</button>
10
<button id="subtract">-</button>
11
<button id="multiply">*</button>
12
<button id="divide">/</button>
13
</form>
关于在js中计算,我写了两种常见方案
39
var b = document.getElementById('num2').value;
40
var a_int = parseInt(a, 10);
41
var b_int = parseInt(b, 10);
42
//调用减法
43
var result = division(a_int,b_int);
//定义两个全局变量 var a_int; var b_int;
//为按钮添加点击方法 addBtn.onclick = function(){
getInputNum(); //调用加法 var result = addition(a_int,b_int); alert(result); } subtractBtn.onclick = function(){ getInputNum(); //调用减法 var result = substraction(a_int,b_int); alert(result); } multiplyBtn.onclick = function(){ getInputNum(); //调用乘法 var result = multiplication(a_int,b_int); alert(result); } divideBtn.onclick = function(){ getInputNum(); //调用减法 var result = division(a_int,b_int); alert(result); } function getInputNum(){ var a = document.getElementById('num1').value; var b = document.getElementById('num2').value; //将转化后的数字赋值给全局变量 a_int = parseInt(a, 10); b_int = parseInt(b, 10); } //构造函数,加减乘除 function addition(x, y){ return x + y; } function substraction(x, y){ return x - y; } function multiplication(x, y){ return x * y; } function division(x, y){ if(y==0){
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
}
#textid{
width: 210px;
height: 30px;
margin: 5px;
font-size: 25px;
padding: 5px;
}
.mainer{
border-style: dotted;
border-color: cadetblue;
padding: 50px 30px;
function addStr(x){
inputvalue.value = inputvalue.value + x;
}
function calculates(){
inputvalue.value = eval(inputvalue.value);
}
function empty(){
inputvalue.value = null;
var minute=document.getElementById('minute');
var second=document.getElementById('seconds');
function showTime(){
var oDate=new Date();
var iHours=oDate.getHours();
list-style-type: none;
display: inline-block;
width: 30px;
heightБайду номын сангаас40px;
text-shadow:0 2px 1px #f4f4f4;
border:1px solid #9fa2ad;
border-radius: 5px;
margin-right:10px;
<td><input class="btn" type="button" onclick="addStr('-')" value="-"></td>
</tr>
<tr>
<td><input class="btn" type="button" onclick="addStr(4)" value="4"></td>
70%{transform: rotate(360deg);left:220px;}
100%{transform: rotate(-360deg);left:0px;}
}
#formid{
text-align: center;
}
#tableid{
margin-left: 10px;
}
body,ul,li{
box-shadow:inset 0 -2px 0 #f1f1f1,0 1px 0 #f1f1f1,0 2px 0 #9fa2ad,0 3px 0 #f1f1f1,0 4px 0 #9fa2ad;
}
.box li span:first-child{
font:15px 'BitstreamVeraSansMonoBold';
background: radial-gradient(#eeefef, #d6d7d9);
padding: 50px;
}
.box{
width: 150px;
height: 80px;
margin: 5px 15px;
}
.box li{
position: relative;
text-align: center;
<td><input class="btn" type="button" onclick="addStr('*')" value="x"></td>
<td><input class="btn" type="button" onclick="del()" value="<"></td>
</tr>
<tr>
}
function del(){
inputvalue.value = inputvalue.value.substr(0,inputvalue.value.length-1);
}
function percent(){
inputvalue.value = inputvalue.value/100;
}
</script>
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>js简易计算器</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
</head>
<body>
</tr>
<tr>
<td><input class="btn" type="button" onclick="percent()" value="%"></td>
<td><input class="btn" type="button" onclick="addStr(0)" value="0"></td>
}
showTime();
setInterval(showTime,1000);
function AddZero(n){
if(n<10){
return '0'+n;
}
return ''+n;
}
</script>
<script>
var inputvalue = document.getElementById("textid");
color: #aaffff;
background: -moz-radial-gradient(#eeefef, #d6d7d9);
background: -o-radial-gradient(#eeefef, #d6d7d9);
background: -ms-radial-gradient(#eeefef, #d6d7d9);
background: -webkit-gradient(linear,0 0, 0 100%,
color-stop(.2,rgba(248,248,248,.3)),
color-stop(.5,rgba(168,173,190,.5)),
color-stop(.51,rgba(168,173,190,.3)),
<td><input class="btn" type="button" onclick="addStr(7)" value="7"></td>
<td><input class="btn"type="button" onclick="addStr(8)" value="8"></td>
<td><input class="btn" type="button" onclick="addStr(9)" value="9"></td>
position: absolute;
left:50%;
top:50%;
margin-left:-125px;
margin-top:-250px;
width: 250px;
height: 400px;
background-image: url(../img/beijing.jpg);/*计算器背景图片,可自行更换*/
<div class="mainer">
<img src="img/1.png" id="animated_div"/>/*动画所用图片元素,可自行更换*/
<form name="form" id="formid">
<input id="textid" type="text" disabled="disabled" placeholder="请输入内容:">
</body>
</html>
Css
.btn{
width: 50px;
height: 50px;
font-size: 16px;
margin: 2px;
cursor: pointer; /*鼠标指针指上去变成小手*/
font-weight: bold;