js-cal网页简易计算器Word文档

合集下载

JavaScript实现简单网页版计算器

JavaScript实现简单网页版计算器

JavaScript实现简单⽹页版计算器背景由于我⼜被分进了⼀个新的项⽬组,该项⽬需要⽤js,因为我没接触过,所以领导准备给我⼀周时间学习,没错,实现⼀个简单的⽀持四则混合运算的计算器就是作业,所以有了这篇⽂章故,这篇⽂章主要重点就不在html和css了,毕竟我也只是略懂⽪⽑,并未深究过实现效果最终展现的页⾯如下图,当⿏标点击按键时,按键会变⾊,可以进⾏四则混合运算上⾯⼀⾏显⽰计算式,当按下“=”时,显⽰计算结果⽤到的技术计算器的页⾯是使⽤html的table绘制的按键的⼤⼩,颜⾊,⿏标悬浮变⾊是⽤css设置的点击按键将按键上的值和计算结果显⽰在最上⾯⼀⾏、完成四则混合运算是⽤js做的实现思路这⾥我分了三个⽂件,⼀个.html ⼀个 .css ⼀个 .js1、先写了html和css,绘制出来⽹页展⽰的样⼦,此处不细说,有兴趣可以直接看代码2、然后⽤js的DOM事件,给不同类型的按钮加上点击事件,调⽤不同的js函数。

这⼀步我开始只是先写了⼀个函数定义,主要是为了先划分清楚逻辑,⽐如按某个按键应该实现哪些功能,显⽰什么效果等,后⾯对函数进⾏填充逻辑就不会乱掉3、最后去实现js函数,也就是完成四则混合运算,重点说⼀下是怎么实现四则混合运算并且让结果显⽰出来的上⾯显⽰算式和结果的时候,我定义了⼀个全局变量的数组,每次点击按键,就把点击的那个按键的值push到数组⾥,这样显⽰的时候就直接把数组丢过去。

这样做的还有⼀个原因是点击退格键的时候就pop⼀下,点击清空键的时候就直接赋个空数组给数组变量,操作起来会容易⼀些接着很重要的⼀步是计算表达式,⽐如说输⼊ 3 * 4.5 - 1= 这样的⼀个表达式,怎么去求值呢,我想到的⽅法是先把输⼊的数组变成变成中缀表达式,再由中缀表达式转成后缀表达式,然后再进⾏后缀表达式求值1. ⾸先通过上⾯的数组处理得到了这样的⼀个数组['3','*','4','.','5','-','1']2. 把这个数组转换成字符串变为这样 “3*4.5-1”3. 接着处理成操作符和数字分开的新的数组 ['3','*','4.5','-','1']4. 处理完之后就是利⽤栈来将中缀表达式变为后缀表达式5. 再利⽤栈对后缀表达式求值,并且将结果填在=之后由于4.5步是数据结构中栈应⽤的内容,不清楚的可以回顾⼀下数据结构,⾄此就全部完成具体实现代码如上,分析的已经够多了,所以这块就话不多说,直接上代码.html⽂件<!DOCTYPE html><html><head><title>calculator</title><link rel="stylesheet" href="calculator.css" ><script src="calculator.js"></script></head><body><div><table border="1"><thead><th colspan="4"><input type="text" id="result" disabled></th></thead><tbody><tr><td><button class="operate" onclick="showNumber(this)">(</button></td><td><button class="operate" onclick="showNumber(this)">)</button></td><td><button class="operate" onclick="clearOneResult()">←</button></td><td><button class="operate" onclick="clearResult()">C</button></td></tr><tr><td><button class="calculate" onclick="showNumber(this)">7</button></td><td><button class="calculate" onclick="showNumber(this)">8</button></td><td><button class="calculate" onclick="showNumber(this)">9</button></td><td><button class="operate" onclick="showNumber(this)">*</button></td></tr><tr><td><button class="calculate" onclick="showNumber(this)">4</button></td><td><button class="calculate" onclick="showNumber(this)">5</button></td><td><button class="calculate" onclick="showNumber(this)">6</button></td><td><button class="operate" onclick="showNumber(this)">-</button></td></tr><tr><td><button class="calculate" onclick="showNumber(this)">1</button></td><td><button class="calculate" onclick="showNumber(this)">2</button></td><td><button class="calculate" onclick="showNumber(this)">3</button></td><td><button class="operate" onclick="showNumber(this)">+</button></td></tr><tr><td><button class="calculate" onclick="showNumber(this)">0</button></td><td><button class="calculate" onclick="showNumber(this)">.</button></td><td><button class="operate" onclick="showNumber(this)">/</button></td> <td><button class="operate" onclick="showAnswer()">=</button></td></tr></tbody></table></div></body></html>.css⽂件table{margin: 20px;padding: 1px;}th,input{height: 120px;width: 410px;background-color:rgb(233, 232, 232);text-align: right;font-size: 40px;}button{height: 100px;width: 100px;padding: 0px;font-size: 30px;}th,input,td,button{border: 0px;}.calculate{background-color: rgb(231, 231, 235);}.operate{color: coral;}button:hover{background-color: rgb(147, 241, 253);}.js⽂件var result = new Array();var ops = "+-*/";function arrToStr(arr) {var strResult = "";for (var i = 0; i < arr.length; i++) {strResult += arr[i];}return strResult;}function showResult() {document.getElementById("result").value = arrToStr(result);}function showNumber(id) {var val = id.innerHTML;result.push(val);showResult();}function showAnswer() {var answer = "";var str = arrToStr(result);var midExpre = strToExpress(str);var suffixExpre = midToSuffix(midExpre);answer = suffixValue(suffixExpre);//console.log(midExpre);//console.log(suffixExpre);document.getElementById("result").value = str + "=" + answer;}function clearResult() {result = [];showResult();}function clearOneResult() {result.pop();showResult();}function strToExpress(str) {var textArr = str.split('');var newTextArr = [];var calTextArr = [];for (var i = 0; i < str.length; i++) {if (ops.indexOf(str[i]) != -1 ) {newTextArr.push("|", str[i], "|");}else if (str[i] == '('){newTextArr.push(str[i], "|");}else if (str[i] == ')'){newTextArr.push("|", str[i]);}else {newTextArr.push(textArr[i]);}}calTextArr = newTextArr.join('').split('|');return calTextArr;}function midToSuffix(midExpre) {var opStack = [];var suffixExpre = [];for (var i = 0; i < midExpre.length; i++) {if (ops.indexOf(midExpre[i]) != -1 || midExpre[i] == '(' || midExpre[i] == ')' ) {if (midExpre[i] == '(' || opStack[opStack.length - 1] == '(') {opStack.push(midExpre[i]);}else if (midExpre[i] == ')') {do {suffixExpre.push(opStack.pop());} while (opStack[opStack.length - 1] != '(');opStack.pop();}else if (opStack.length == 0 || Priority(midExpre[i]) > Priority(opStack[opStack.length - 1])) { opStack.push(midExpre[i]);}else {do {suffixExpre.push(opStack.pop());} while (opStack.length > 0 && Priority(midExpre[i]) <= Priority(opStack[opStack.length - 1])); opStack.push(midExpre[i]);}}else {suffixExpre.push(midExpre[i]);}}while (opStack.length > 0) {suffixExpre.push(opStack.pop());}return suffixExpre;}function Priority(op) {var opPri = 0;switch (op) {case "+":opPri = 1;break;case "-":opPri = 1;break;case "*":opPri = 2;break;case "/":opPri = 2;break;}return opPri;}function suffixValue(suffixExpre) {var calStack = [];console.log(suffixExpre);for (var i = 0; i < suffixExpre.length; i++) {if (ops.indexOf(suffixExpre[i]) != -1) {var opRight = Number(calStack.pop());var opLeft = Number(calStack.pop());var tmpResult = 0;switch (suffixExpre[i]) {case '+':tmpResult = opLeft + opRight;break;case '-':tmpResult = opLeft - opRight;break;case '*':tmpResult = opLeft * opRight;break;case '/':tmpResult = opLeft / opRight;break;}calStack.push(tmpResult);}else {calStack.push(suffixExpre[i]);}console.log(calStack);}return calStack.pop();}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

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种方法

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计算器⽹页版实现代码分享JavaScript⽹页计算器代码,该计算器是⽤DW写的!HTML篇<html<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>计算器</title><link href="style/calculator.css" rel="stylesheet" type="text/css" /><script src="JavaScript/calculator.js"></script>></head><body ><form id="form1" name="form1" method="post" action=""><table width="320" border="1" cellpadding="0" cellspacing="0" class="trb" id="calculator"><tr><td height="100" colspan="4" align="left" valign="top"><label for="txt"></label><input name="txt" type="text" class="txt" id="txt" value="0" onfocus="this.blur();"/></td></tr><tr><td width="80" height="40" align="center" valign="middle" onclick="deleteAll();">C</td><td width="80" height="40" align="center" valign="middle" onclick="Backspace();">←</td><td width="80" height="40" align="center" valign="middle" onclick="sign();">±</td><td width="80" height="40" align="center" valign="middle" class="operator" onclick="add();">+</td></tr><tr><td width="80" height="40" align="center" valign="middle" onclick="command(7);">7</td><td width="80" height="40" align="center" valign="middle" onclick="command(8);">8</td><td width="80" height="40" align="center" valign="middle" onclick="command(9);">9</td><td width="80" height="40" align="center" valign="middle" class="operator" onclick="subtract();">-</td></tr><tr><td width="80" height="40" align="center" valign="middle" onclick="command(4);">4</td><td width="80" height="40" align="center" valign="middle" onclick="command(5);">5</td><td width="80" height="40" align="center" valign="middle" onclick="command(6);">6</td><td width="80" height="40" align="center" valign="middle" class="operator" onclick="multiply();">×</td></tr><tr><td width="80" height="40" align="center" valign="middle" onclick="command(1);">1</td><td width="80" height="40" align="center" valign="middle" onclick="command(2);">2</td><td width="80" height="40" align="center" valign="middle" onclick="command(3);">3</td><td width="80" height="40" align="center" valign="middle" class="operator" onclick="divide();">÷</td></tr><tr><td width="80" height="40" align="center" valign="middle" onclick="command(0);">0</td><td width="80" height="40" align="center" valign="middle" onclick="dot();">▪</td><td height="40" colspan="2" align="center" valign="middle" bgcolor="#CC6600" onclick="equal();">=</td></tr></table><p> </p><p> </p></form></body></html>CSS篇@charset "utf-8";/* CSS Document */.trb {font-family: Georgia, "Times New Roman", Times, serif;font-size: 24px;color: #FFF;background-color: #333;text-align: center;border: 1px solid #999;}.operator {background-color: #333;font-size: 18px;font-family: Verdana, Geneva, sans-serif;}td:hover{font-size: 28px;cursor:pointer;}.txt {height: 100px;width: 320px;background-color: #333;text-align: left;vertical-align: bottom;color: #FFF;font-size: 30px;}JavaScript篇//实现计算器功能//结果var result = 0;//显⽰框中的数(默认为“0”)var screenNum = "0";//数的初始输⼊状态,默认为0;当按了任意运算符键后,数的输⼊状态变为1var state = 0;//防⽌重复按运算符键var avoidRepeat = true;//运算符键(默认为0--等于号)var operator = 0;//第⼀步:获取按键值,并显⽰在显⽰框中function command(num) {//获取显⽰框的值var str = String(document.form1.txt.value);//对该值进⾏判断,如果该值不为"0",且输⼊状态0,则返回前者,否则为""(双重三⽬运算) //两个判断条件:1、显⽰框中值是否为"0", 2、数的输⼊状态str = (str != "0")?((state == 0)?str:""):"";//给当前值追加字符str = str + String(num);//刷新显⽰document.form1.txt.value = str;//按了任意数字键后,数的输⼊状态变为0state = 0;//重置防⽌重复按键avoidRepeat = true;}//第⼆步:确保输⼊的数是合法的,每个数⾄多只有⼀个⼩数点function dot() {var str = String(document.form1.txt.value);//若该数前⾯未接运算符,则返回前值,否则为"0";str = (state == 0)?str:"0";//Java⾥String有length()⽅法,⽽JS⾥String有length属性for(i=0;i<=str.length;i++) {//substr()获取下标从i开始,个数为1个的⼦串if(str.substr(i,1)==".") {//当存在⼩数点时,则程序终⽌return;}}//若⽆⼩数点,则在该数后⾯加上str = str+".";//刷新显⽰document.form1.txt.value = str;//恢复数的初始输⼊状态state = 0;}//第三步:处理退格键function Backspace() {var str= String(document.form1.txt.value);//若显⽰框中数不等于"0",则返回str,否则返回""str = (str != "0")?str:"";str = str.substr(0,str.length-1);//若str不为"",则返回⼦串str,否则str="0" str = (str != "")?str:"0";//刷新显⽰document.form1.txt.value = str;}//第四步:删除所有function deleteAll() {//显⽰框设为"0"document.form1.txt.value = "0";//恢复数的初始输⼊状态state = 0;//恢复运算符键,默认为0--等于号operator = 0;}//第五步:加法function add() {//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//更改运算符键,1--加号operator = 1;}//第六步:减法function subtract() {//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//2--减号operator = 2;}//第七步:乘法function multiply() {//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//3--乘号operator = 3;}//第⼋步:除法function divide() {//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//4--除号operator = 4;}//第九步:正负号function sign() {//5--正负号operator = 5;//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//0--等于号operator = 0;//正负号可以连续按avoidRepeat = true;}//第⼗步:等于function equal() {//调⽤计算函数calculate();//更改数的输⼊状态state = 1;//0--等于号operator = 0;}//第⼗⼀步:计算function calculate() {//获取显⽰框中的值screenNum = Number(document.form1.txt.value);if(avoidRepeat) {switch(operator){case 1:result = result + screenNum;document.form1.txt.value = result;break;case 2:result = result - screenNum;document.form1.txt.value = result;break;case 3:result = result * screenNum;document.form1.txt.value = result;break;case 4:if(screenNum == 0){//设置显⽰框的值document.getElementById("txt").value="除数不能为0";//3s后,执⾏清屏函数setTimeout(clearScreen,3000);}else{result = result/screenNum;document.form1.txt.value = result;}break;case 5:result = (-1)*screenNum;document.form1.txt.value = result;break;case 0:result = screenNum;document.form1.txt.value = result;break;}//当按了运算符键后,不能再按avoidRepeat = false;}}//第⼗⼆步:清屏函数function clearScreen() {document.getElementById("txt").value = "0";}关于计算器的精彩⽂章请查看,更多精彩等你来发现!以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

《java简易计算器》Word文档

《java简易计算器》Word文档

//只可以做简易的加减乘除运算//每次运算结束之后必须按一下清除才可以进行第二次运算import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowAdapter;import java.awt.event.WindowEvent;import java.awt.Event;public class Calculator {Button[] bt = new Button[10];//数字键Button bp,bj,bc,bu,bq,be;//分别对应的是加,减,乘,除,清除,等于public String numCache="";//缓存拿到的值,这个地方如果不赋初值的话会报错,就是必须在第一次使用前按下清除键public int num1,num2;//参加运算的值public String showNum="";//文本框显示的值public String operator="";//显示的运算符TextField tf;//文本框public int result;public static void main(String[] args) {new Calculator().setFrame();}/*frame*/public void setFrame() {Frame mFrame = new Frame("java简易计算器");//窗口Panel p1 = new Panel();//文本框的容器tf = new TextField(30);//文本框p1.add(tf);//添加文本框进入容器mFrame.add(p1,BorderLayout.NORTH);//将p1放到mFrame的北区域Panel p2 = new Panel();//存放button的容器p2.setLayout(new GridLayout(4,4));//放置button的p2容器,默认添加到center区//添加按钮bt[0] = new Button("0");bt[1] = new Button("1");bt[2] = new Button("2");bt[3] = new Button("3");bt[4] = new Button("4");bt[5] = new Button("5");bt[6] = new Button("6");bt[7] = new Button("7");bt[8] = new Button("8");bt[9] = new Button("9");bp = new Button("+");bj = new Button("-");bc= new Button("*");bu= new Button("/");bq= new Button("清除");be= new Button("=");//将button添加进panelfor(int i=0;i<10;i++) {p2.add(bt[i]);}p2.add(bp);p2.add(bj);p2.add(bc);p2.add(bu);p2.add(bq);p2.add(be);bp.addActionListener(new Monitor());bj.addActionListener(new Monitor());bc.addActionListener(new Monitor());bu.addActionListener(new Monitor());bq.addActionListener(new Monitor());be.addActionListener(new Monitor());mFrame.add(p2);mFrame.pack();//注册监听器类for(int i=0;i<10;i++) {bt[i].addActionListener(new Monitor());}mFrame.setBackground(Color.GRAY);//窗口的背景颜色mFrame.setVisible(true);//显示窗口mFrame.addWindowListener(new WindowAdapter(){//窗口的关闭事件public void windowClosing(WindowEvent e) {System.exit(-1);}});}//frame构造方法结束,第9行开始//事件监听class Monitor implements ActionListener {public void actionPerformed(ActionEvent e) {Button b = (Button)e.getSource();String str = b.getActionCommand();//如果按下的是运算符if(str.equals("+")||str.equals("-")||str.equals("*")||str.equals("/")) {//按下的是运算符if((numCache)!="") {num1 = Integer.parseInt(numCache);}operator = str;tf.setText(operator);numCache = "";showNum = "";//如果按下的是清除键}else if(str.equals("清除")) {showNum = "";numCache="";tf.setText("0.");//如果按下的是等号}else if(str.equals("=")) {num2 = Integer.parseInt(numCache);if(operator.equals("+")) {result = num1+num2;}else if(operator.equals("-")) {result = num1-num2;}else if(operator.equals("*")) {result = num1*num2;}else{if(num2==0) {tf.setText("被除数不能为零");return;}result = num1/num2;}tf.setText(result+"");num1 = 0;num2 = 0;result = 0;}else {//如果按下的是数字showNum = showNum+b.getActionCommand();numCache = numCache+b.getActionCommand();tf.setText(showNum);}}}}//bug报告:(注:素材和资料部分来自网络,供参考。

超级简易的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: 100px 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应用实例

javascript应用实例

javascript应用实例JavaScript应用实例:制作一个简单的计算器JavaScript是一种广泛应用于网页开发的脚本语言,它可以为网页添加动态效果和交互性。

在本文中,我们将介绍如何使用JavaScript 制作一个简单的计算器。

我们需要在HTML文件中创建一个表单,其中包含数字和运算符按钮以及一个显示结果的文本框。

代码如下:```<form><input type="text" id="result" readonly><br><input type="button" value="1" onclick="addNumber(1)"><input type="button" value="2" onclick="addNumber(2)"><input type="button" value="3" onclick="addNumber(3)"><input type="button" value="+" onclick="addOperator('+')"><br><input type="button" value="4" onclick="addNumber(4)"><input type="button" value="5" onclick="addNumber(5)"><input type="button" value="6" onclick="addNumber(6)"><input type="button" value="-" onclick="addOperator('-')"><br><input type="button" value="7" onclick="addNumber(7)"><input type="button" value="8" onclick="addNumber(8)"><input type="button" value="9" onclick="addNumber(9)"><input type="button" value="*" onclick="addOperator('*')"><br><input type="button" value="0" onclick="addNumber(0)"><input type="button" value="C" onclick="clearResult()"><input type="button" value="=" onclick="calculate()"><input type="button" value="/" onclick="addOperator('/')"></form>```在这个表单中,我们使用了四个数字按钮、四个运算符按钮和一个清除按钮。

JavaScript编写的简易计算器

JavaScript编写的简易计算器
</td>
<td>
<input type="button" style="width:40px" value="pi" onclick="cal.totoal.value=Math.PI">
</td>
<td>
<input type="button" style="width:40px" value="E" onclick="cal.total.value=Math.E">
</td>
<td>
<input type="button" style="width:40px" value="7" onclick="addNum('7')">
</td>
<td>
<input type="button" style="width:40px" value="8" onclick="addNum('8')">
preOper=true;
break;
case "asin":
cal.total.value=Math.asin(cal.total.value);
preOper=true;
break;
case "acos":
cal.total.value=Math.acos(cal.total.value);

利用JavaScript写一个简单计算器

利用JavaScript写一个简单计算器

利⽤JavaScript写⼀个简单计算器效果如下:参考程序:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>模拟计算器</title><style>button {width: 39px;height: 30px;background-color: rgb(102, 240, 102);}button:hover {background-color: black;color: rgb(255, 249, 237);}button:active {background-color: rgb(79, 72, 72);color: white;}table{background: rgb(192, 248, 109);}</style></head><body><div><table border="1px"><tr style="text-align: center;"><td colspan="4"><input type="text" id="result" ></td></tr><tr><td><button id="le" onclick="getChar('(')">(</button></td><td><button id="rg" onclick="getChar(')')">)</button></td><td><button id="baifen" onclick="getChar('%')">%</button></td> <td><button id="C" onclick="clear1()">C</button></td></tr><tr><td><button id="seven" onclick="getChar('7')">7</button></td> <td><button id="eight" onclick="getChar('8')">8</button></td> <td><button id="nine" onclick="getChar('9')">9</button></td><td><button id="divi" onclick="getChar('/')">/</button></td></tr><tr><td><button id="four" onclick="getChar('4')">4</button></td><td><button id="five" onclick="getChar('5')">5</button></td><td><button id="six" onclick="getChar('6')">6</button></td><td><button id="mul" onclick="getChar('*')">*</button></td></tr><tr><td><button id="one" onclick="getChar('1')">1</button></td><td><button id="two" onclick="getChar('2')">2</button></td><td><button id="three" onclick="getChar('3')">3</button></td> <td><button id="dec" onclick="getChar('-')">-</button></td></tr><tr><td><button id="zero" onclick="getChar('0')">0</button></td><td><button id="point" onclick="getChar('.')">.</button></td><td><button id="=" onclick="getResult()">=</button></td><td><button id="add" onclick="getChar('+')">+</button></td></tr></table></div></body><script>// 点击按键返回按键值function getChar(btnid) {var btns = document.getElementsByTagName("button") switch (btnid) {case '+':setNum('+')break;case '.':setNum('.')break;case '=':setNum('=')break;case '0':setNum('0')break;case '1':setNum('1')break;case '2':setNum('2')break;case '3':setNum('3')break;case '-':setNum('-')break;case '4':setNum('4')break;case '5':setNum('5')break;case '6':setNum('6')break;case '7':setNum('7')break;case '8':setNum('8')break;case '9':setNum('9')break;case '/':setNum('/')break;case '*':setNum('*')break;case '(':setNum('(')break;case ')':setNum(')')break;case '%':setNum('%')break;default:break;}}// 清空显⽰屏function clear1() {document.getElementById("result").value = "" }// 将数值显⽰到显⽰屏function setNum(charCode) {var origin = document.getElementById('result'); origin.value += charCode;origin.innerText = origin.value;}// 计算结果function getResult(){var res=eval(document.getElementById("result").value);// 追加'='setNum('=');// 追加结果setNum(res)}</script></html>备注:在做计算的时候,可以直接使⽤eval这个函数,我们就不⽤⾃⼰⼿动写加减乘除的计算逻辑了,⼤⼤简化了开发例如:var num=eval(‘3+3')则运算结果是num=6eval函数⽤法:语法:eval(参数),参数是js表达式,为字符串,可以包含变量以及已经存在对象的属性返回值情况:参数类型返回值整数或者函数整数或函数字符串(且是表达式)该字符串表达式的运⾏结果字符串(且是语句或者语句块)执⾏该语句块并返回undefined到此这篇关于利⽤JavaScript写⼀个简单计算器的⽂章就介绍到这了,更多相关JavaScript写简单计算器内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

信息技术作业使用JavaScript实现一个简单的计算器程序

信息技术作业使用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实现简易计算器⽤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>这样就圆满完成咯以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

JS——制作简单的网页计算器

JS——制作简单的网页计算器

JS——制作简单的⽹页计算器⽤JS做了⼀个简易的⽹页计算器<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>计算器</title><script type="text/javascript">window.onload = function () {var oInput01 = document.getElementById('input01');var oInput02 = document.getElementById('input02');var oFuhao = document.getElementById('fuhao');var oBtn = document.getElementById('btn');oBtn.onclick = function(){var num01 = oInput01.value;var num02 = oInput02.value;var fuhao = oFuhao.value;//验证是否为空if(num01==''||num02==''){alert('输⼊框不能为空!');return;}if(isNaN(num01)||isNaN(num02)){alert('请输⼊数字!');return;}switch (fuhao){//这个value是字符串!case "0":alert((parseFloat(num01)*100+parseFloat(num02)*100)/100);break;case '1':alert((parseFloat(num01)*100-parseFloat(num02)*100)/100);break;case "2":alert(((parseFloat(num01)*100)*(parseFloat(num02)*100))/10000);break;case '3':alert(((parseFloat(num01)*100)/(parseFloat(num02)*100)));}}}</script></head><body><h1>计算器</h1><input type="text" name="" id="input01"><select id="fuhao"><option value="0">+</option><option value="1">-</option><option value="2">*</option><option value="3">/</option></select><input type="text" name="" id="input02"><input type="button" name="" value="计算" id="btn"></body></html>。

基于JavaScript实现简易计算器

基于JavaScript实现简易计算器

基于JavaScript实现简易计算器本⽂实例为⼤家分享了JavaScript实现简易计算器的具体代码,供⼤家参考,具体内容如下<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>计算器</title><style>.op {margin: 50px auto;width: 300px;height: 300px;border: 1px solid orange;background-color: lightskyblue;border-radius: 50px;}input {width: 210px;height: 30px;border-radius: 5px;}button {width: 30px;height: 30px;border-radius: 10px;}</style></head><body><div class="op"><h2 align="center">计算器</h2><form name="calculator"><table align="center"><tr><td>num1:</td><td><input type="text" name="num1"></td></tr><tr><td>num2:</td><td><input type="text" name="num2"></td></tr><tr><td colspan="2">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<button type="button">+</button>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<button type="button">-</button>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<button type="button">*</button>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<button type="button">/</button></td></tr><tr><td>结果:</td><td><input type="text" name="result" disabled></td></tr></table></form></div><script>//得到标签名下的所有元素对象,返回⼀个数组let buttonArr = document.getElementsByTagName("button");for (let but of buttonArr) {but.addEventListener('click', function () {let operator = this.innerHTML;count(operator);});}function count(operator) {//得到form为calculator中name为num1的输⼊值let num1 = parseFloat(document.calculator.num1.value);let num2 = parseFloat(document.calculator.num2.value);let result = '';switch (operator) {case '+':result = num1 + num2;break;case '-':result = num1 - num2;break;case '*':result = num1 * num2;break;case '/':if (num2 == 0) {alert("除数不能为零");return;}result = num1 / num2;break;}//将结果赋值于属性名name为result的input框document.calculator.result.value = result;}</script></body></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

网页计算器 javascript

网页计算器   javascript
try{m+=s2.split(".")[1].length}catch(e){}
return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m)
}
//浮点数除法运算
function FloatDiv(arg1,arg2){
//document.calc.display.scrollLeft = document.calc.display.scrollWidth;/* for ie */
var index=key.charCodeAt(0);
if ((carry == 2 && (index == 48 || index == 49)) || (carry == 8 && index >= 48 && index <= 55) || (carry == 10 && (index >= 48 && index <= 57 || index == 46)) || (carry == 16 && ((index >= 48 && index <= 57) || (index >= 97 && index <= 102))))
.calculator_tab ul {list-style:none;width:100%;height:100%;margin:0px;padding:0px;}
.calculator_tab ul li {height:31px;width:100%;color:#FFF;text-align:center;cursor:pointer;line-height:240%;}

JavaScript实现简单计算器

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实现简单的计算器功能本⽂实例为⼤家分享了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;">数&nbsp;&nbsp;字1:<input id="num1" type="number" placeholder="请输⼊数字1"></div></div><div><div class="innerDiv" style="margin-left:490px;">数&nbsp;&nbsp;字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="相&nbsp;&nbsp;加"><input type="button" onclick="myck(2)" value="相&nbsp;&nbsp;减"><input type="button" onclick="myck(3)" value="相&nbsp;&nbsp;乘"><input type="button" onclick="myck(4)" value="清&nbsp;&nbsp;空"></div></div><div id="resultDiv"></div></body><style>.innerDiv{margin-left: 420px;margin-top: 20px;}</style></html>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

最新js-cal网页简易计算器

最新js-cal网页简易计算器
给各个按钮进行算法,利用鼠标点击事件,当鼠标点击某个按钮时就开始执行那个按钮所定义的算法,生成数据并显示。
除数字的输入为直接进行输入外,其他运算例如+、-、*、/、开平方等算法要求计算时通过内部较为复杂的运算将结果显示在显<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<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>
function getResult(){
var objresult2=document.getElementById("result");
//为结果赋值
objresult2.value=objresult2.value+"="+eval(objresult2.value);
clearContent=true;
<td width="23%"><input type="button" value=" 2 " onclick="getNum(2)"></td>

js制作简易计算器

js制作简易计算器

js制作简易计算器本⽂实例为⼤家分享了js制作简易计算器的具体代码,供⼤家参考,具体内容如下要制作⼀个如图所⽰的简易计算器,⾸先要建⽴⼀个表单,制作出如图所⽰的样⼦。

<table border="1" cellspacing="0" ><tr><th colspan="2">购物简易计算器</th></tr><tr><td>第⼀个数</td><td><input type="text" id="inputId1" /></td></tr><tr><td>第⼆个数</td><td><input type="text" id="inputId2" /></td></tr><tr><td><button type="button" onclick="cal('+')" >+</button></td><td><button type="button" onclick="cal('-')" >-</button><button type="button" onclick="cal('*')" >*</button><button type="button" onclick="cal('/')" >/</button></td></tr><tr><td>计算结果</td><td><input type="text" id="resultId"/></td></tr></table>onclick使⽤cal()⽅法,其实⼀开始我是使⽤add,sub,mul,div四种⽅法的,后来发现这四个⽅法除了算术运算符不⼀样,其他的地⽅都⼀样,所以选择使⽤⼀个⽅法,点击button,传给⽅法⾥的算术运算符不⼀样,代码如下:<script type="text/javascript">function cal(type){var num1 = document.getElementById('inputId1');var num2 = document.getElementById('inputId2');var result;switch(type){case '+':result = parseInt(num1.value) + parseInt(num2.value);break;case '-':result = parseInt(num1.value) - parseInt(num2.value);break;case '*':result = parseInt(num1.value) * parseInt(num2.value);break;case '/':result = parseInt(num1.value) / parseInt(num2.value);break;}var resultObj = document.getElementById('resultId');resultObj.value = result;}</script>以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

js实现简单计算器

js实现简单计算器

js实现简单计算器参考部分资料,编写⼀个简单的计算器案例,虽然完成了正常需求,但是也有不满之处,待后续实⼒提升后再来补充,先把不⾜之处列出: 1:本来打算只要打开页⾯,计算器的输⼊框会显⽰⼀个默认为0的状态,但是在输⼊框加⼊默认显⽰为0的时候,选择数据输⼊时,该0会显⽰输⼊数字的前⾯,例如”0123“,由于能⼒有限,待后续实⼒提升再来补充完善! 2:⽬前只能实现⿏标控制选择按钮,待完善键盘录⼊功能。

3:乘法的那个符号在本来想改成”ד这个符号的,待后续完善。

附图⽚⼀张: html部分:<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>计算器</title></head><body onload="onLoad()"><div id="calculator"><div class="LOGO"><span class="name">简单的计算器</span><span class="verson">@liumobai v1.0</span></div><div id="shuRu"><!--screen输⼊栏--><div class="screen"><input type="text" id="screenName" name="screenName" class="screen" value="" onfocus="jsq(this)"></div></div><div id="keys"><!-- operators and other keys --><!--第⼀排--><input type="button" id="7" onclick="jsq(this.id)" value="7" class="buttons"><input type="button" id="8" onclick="jsq(this.id)" value="8" class="buttons"><input type="button" id="9" onclick="jsq(this.id)" value="9" class="buttons"><input type="button" id="Back" onclick="tuiGe()" value="Back" class="buttons"><input type="button" id="C" onclick="clearNum()" value="C" class="buttons" style="margin-right:0px"><!--第⼆排--><input type="button" id="/" onclick="jsq(this.id)" value="/" class="buttons" style="margin-right:0px"><!--第三排--><input type="button" id="1" onclick="jsq(this.id)" value="1" class="buttons"><input type="button" id="2" onclick="jsq(this.id)" value="2" class="buttons"><input type="button" id="3" onclick="jsq(this.id)" value="3" class="buttons"><input type="button" id="+" onclick="jsq(this.id)" value="+" class="buttons"><input type="button" id="-" onclick="jsq(this.id)" value="-" class="buttons" style="margin-right:0px"><!--第四排--><input type="button" id="0" onclick="jsq(this.id)" value="0" class="buttons"><input type="button" id="00" onclick="jsq(this.id)" value="00" class="buttons"><input type="button" id="." onclick="jsq(this.id)" value="." class="buttons"><input type="button" id="%" onclick="jsq(this.id)" value="%" class="buttons"><input type="button" id="eva" onclick="eva()" value="=" class="buttons" style="margin-right:0px"></div><div class="footer"><span class="aside">欢迎使⽤JavaScript计算器</span><span class="link"><a href="#" title="声明" target="_blank">反馈</a></span></div></div></body></html> JS部分:<script>var num = 0; // 定义第⼀个输⼊的数据function jsq(num) {//获取当前输⼊document.getElementById('screenName').value += document.getElementById(num).value;}function eva() {//计算输⼊结果document.getElementById("screenName").value = eval(document.getElementById("screenName").value); }function clearNum() {//清0document.getElementById("screenName").value = null;document.getElementById("screenName").focus();}function tuiGe() {//退格var arr = document.getElementById("screenName");arr.value = arr.value.substring(0, arr.value.length - 1);}function onLoad(){//加载完毕后光标⾃动对应到输⼊框document.getElementById("screenName").focus();}</script> CSS部分: /*Basic reset*/*{margin:0;padding:0;box-sizing: border-box;font: 14px Arial,sans-serif;}html{height:100%;background-color:lightslategrey;}#calculator{margin: 15px auto;width:330px;height:400px;/*LOGO*/.LOGO{height:20px;}.LOGO .name{float:left;line-height:30px;}.LOGO .verson{float:right;line-height:30px;}/*screen*/#shuRu{margin-top:15px;}.screen{margin-top:5px;width:300px;height:40px;text-align: right;padding-right:10px;font-size:20px;}#keys{border:1px solid lightgray;height:223px;margin-top:25px;padding:8px;}#keys .last{margin-right:0px;}.footer{margin-top:20px;height:20px;}.footer .link{float:right;}#keys .buttons{float:left;width: 42px;height: 36px;text-align:center;background-color:lightgray;margin: 0 17px 20px 0;}接下来再给⼤家分享⼀则实例<html><head><title>Untitled</title><style type="text/css">input[type=button]{width:25px;height:25px;}</style><script type="text/javascript">var result=0;var point=false; //判断是⼩数点前还是后 var multiple=0.1; //初始化⼩数点后的倍率 var sort=0; //标记加减乘除var temp=0; //记录上⼀轮结果function onbutton0() //数字按钮动作{result=result+multiple*0;multiple=multiple*0.1;}name.value=String(result);}function onbutton1(){var name=document.getElementByIdx_x("show"); if(!point) result=10*result+1;else{result=result+multiple*1;multiple=multiple*0.1;}name.value=String(result);}function onbutton2(){var name=document.getElementByIdx_x("show"); if(!point) result=10*result+2;else{result=result+multiple*2;multiple=multiple*0.1;}name.value=String(result);}function onbutton3(){var name=document.getElementByIdx_x("show"); if(!point) result=10*result+3;else{result=result+multiple*3;multiple=multiple*0.1;}name.value=String(result);}function onbutton4(){var name=document.getElementByIdx_x("show"); if(!point) result=10*result+4;else{result=result+multiple*4;multiple=multiple*0.1;}name.value=String(result);}function onbutton5(){var name=document.getElementByIdx_x("show"); if(!point) result=10*result+5;else{result=result+multiple*5;multiple=multiple*0.1;}name.value=String(result);}function onbutton6(){var name=document.getElementByIdx_x("show"); if(!point) result=10*result+6;else{result=result+multiple*6;multiple=multiple*0.1;}name.value=String(result);}function onbutton7(){{result=result+multiple*7;multiple=multiple*0.1;}name.value=String(result);}function onbutton8(){var name=document.getElementByIdx_x("show");if(!point) result=10*result+8;else{result=result+multiple*8;multiple=multiple*0.1;}name.value=String(result);}function onbutton9(){var name=document.getElementByIdx_x("show");if(!point) result=10*result+9;else{result=result+multiple*9;multiple=multiple*0.1;}name.value=String(result);}function onbutton_point() //⼩数点按钮{var name=document.getElementByIdx_x("show");point=true;name.value=String(result)+".";}function onbutton_back() //退格按钮{var name=document.getElementByIdx_x("show");var temp=name.value;name.value="";for(var i=0;i<temp.length-1;i++)name.value+=temp[i];}function onbutton_plus(){var name=document.getElementByIdx_x("show");point=false;multiple=0.1;switch (sort) //遇到下⼀个操作符时判断上⼀个操作符是什么,并进⾏上⼀个操作符的计算{ //eg:1+2+3= 遇到第⼆个+时判断前⼀个符号,发现是+则进⾏+运算,得到3赋给result case 1:result=result+temp;break;case 2:result=temp-result;break;case 3:result=temp*result;break;case 4:result=temp/result;break;}sort=1;temp=result;result=0;name.value="0";}function onbutton_minus(){var name=document.getElementByIdx_x("show");point=false;multiple=0.1;switch (sort){case 1:result=result+temp;break;case 2:result=temp-result;case 4:result=temp/result;break;}sort=2;temp=result;result=0;name.value="0";}function onbutton_mult(){var name=document.getElementByIdx_x("show"); point=false;multiple=0.1;switch (sort){case 1:result=result+temp;break;case 2:result=temp-result;break;case 3:result=temp*result;break;case 4:result=temp/result;break;}sort=3;temp=result;result=0;name.value="0";}function onbutton_div(){var name=document.getElementByIdx_x("show"); point=false;multiple=0.1;switch (sort){case 1:result=result+temp;break;case 2:result=temp-result;break;case 3:result=temp*result;break;case 4:result=temp/result;break;}sort=4;temp=result;result=0;name.value="0";}function onbutton_equal(){var name=document.getElementByIdx_x("show"); point=false; //重置multiple=0.1; //重置switch (sort){case 1:result=result+temp;break;case 2:result=temp-result;break;case 3:result=temp*result;break;case 4:result=temp/result;break;}sort=0; //重置temp=result;result=0;name.value=String(temp);}function onbutton_clear() //重置为初始状态{sort=0; //标记加减乘除temp=0; //记录上⼀轮结果var name=document.getElementByIdx_x("show");name.value="0";}</script></head><body><table align="center"><tr><td colspan="5"><input type="text" value="0" id="show"></td></tr><tr><td><input type="button" value="7" onclick="onbutton7();"></td><td><input type="button" value="8" onclick="onbutton8();"></td><td><input type="button" value="9" onclick="onbutton9();"></td><td><input type="button" value="/" onclick="onbutton_div();"></td><td><input type="button" value="<" onclick="onbutton_back();"></td></tr><tr><td><input type="button" value="4" onclick="onbutton4();"></td><td><input type="button" value="5" onclick="onbutton5();"></td><td><input type="button" value="6" onclick="onbutton6();"></td><td><input type="button" value="*" onclick="onbutton_mult();"></td><td><input type="button" value="C" onclick="onbutton_clear();"></td></tr><tr><td><input type="button" value="1" onclick="onbutton1();"></td><td><input type="button" value="2" onclick="onbutton2();"></td><td><input type="button" value="3" onclick="onbutton3();"></td><td><input type="button" value="-" onclick="onbutton_minus();"></td><td rowspan="2"><input type="button" value="=" style="width:25px;height:57px;" onclick="onbutton_equal();"></td> </tr><tr><td colspan="2"><input type="button" value="0" style="width:57px;height:25px;" onclick="onbutton0();"></td><td><input type="button" value="." onclick="onbutton_point();"></td><td><input type="button" value="+" onclick="onbutton_plus();"></td></tr></table></body></html>。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

JS-简易计算器
一、要求:在网页中编程实现一个简单的计算器,它能提供加减乘除四则运算,它支持IE
浏览器。

二、实验原理(简单步骤)
利用Java Applet图形界面首先开始设计一个计算器的界面,定义计算器所需要的按钮并赋给其按钮名称,使得使用计算器时简单明了,清晰可见,操作轻松。

给各个按钮进行算法,利用鼠标点击事件,当鼠标点击某个按钮时就开始执行那个按钮所定义的算法,生成数据并显示。

除数字的输入为直接进行输入外,其他运算例如+、-、*、/、开平方等算法要求计算时通过内部较为复杂的运算将结果显示在显示屏上。

三、程序界面
四、界面编码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>简易计算器</title>
</head>
<body>
<table width="33%" height="193" border="1">
<tr>
<td colspan="4"><input type="text" size="50" name="result" id="result"></td> </tr>
<tr>
<td width="24%"><input type="button" value=" 1 " onclick="getNum(1)"></td>
<td width="23%"><input type="button" value=" 2 " onclick="getNum(2)"></td>
<td width="26%"><input type="button" value=" 3 " onclick="getNum(3)"></td>
<td width="27%"><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>
<script type="text/javascript" language="javascript">
//判断是否清空
var clearContent=false;
//获得数字
function getNum(num){
if(clearContent){
//如果已经有结果存在则将其清空
document.getElementById("result").value="";
clearContent=false;
}
//获取结果对象
var objresult=document.getElementById("result");
//实现数字连接
objresult.value+=num;
}
//获取结果对象值
function getResult(){
var objresult2=document.getElementById("result");
//为结果赋值
objresult2.value=objresult2.value+"="+eval(objresult2.value);
clearContent=true;
}
</script>
</body>
</html>
(注:素材和资料部分来自网络,供参考。

请预览后才下载,期待你的好评与关注!)。

相关文档
最新文档