一个计算器js脚本
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实现简单计算器的具体代码,供⼤家参考,具体内容如下设计⼀个简单的计算器代码<body><a>第⼀个数</a><input type="test" id="inputId1" value="" /><br/><a>第⼆个数</a><input type="test" id="inputId2" value="" /><br/><button onclick="cal('+')">+</button><button onclick="cal('-')">-</button><button onclick="cal('*')">*</button><button onclick="cal('/')">/</button><br/><a>计算结果</a><input type="test" id="resultId" value="" /><script type="text/javascript">// function add() {// console.log('add');// var inputObj1 = document.getElementById('inputId1');// var inputObj2 = document.getElementById('inputId2');// var result = parseInt(inputObj1.value) + parseInt(inputObj2.value);// var resultObj = document.getElementById('result');// resultObj.value = result;// console.log(result);// }function cal(type) {var inputObj1 = document.getElementById('inputId1');var inputObj2 = document.getElementById('inputId2');switch(type){case '+':var result = parseInt(inputObj1.value) + parseInt(inputObj2.value);break;case '-':var result = parseInt(inputObj1.value) - parseInt(inputObj2.value);break;case '*':var result = parseInt(inputObj1.value) * parseInt(inputObj2.value);break;case '/':var result = parseInt(inputObj1.value) / parseInt(inputObj2.value);break;}var resultObj = document.getElementById('resultId');resultObj.value = 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编写的计算器
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD><META charset="UTF-8"><TITLE>计算器</TITLE><META NAME="Generator" CONTENT="EditPlus"><META NAME="Author" CONTENT="yqy"><META NAME="Keywords" CONTENT="yqy"><META NAME="Description" CONTENT=""></HEAD><BODY ><table border="1px"><tr><td colspan="4"><input type="text" id="one"/></td></tr><tr><td colspan="2"><input type="button" value="CE" onclick="cle()"/></td><td colspan="2"><input type="button" value="Backspace" onclick="ba()"/></td> </tr><tr><td><input type="button" value="7" onclick="add(7)"/></td><td><input type="button" value="8" onclick="add(8)"/></td><td><input type="button" value="9" onclick="add(9)"/></td><td><input type="button" value="/" onclick="add('/')"/></td></tr><tr><td><input type="button" value="4" onclick="add(4)"/></td><td><input type="button" value="5" onclick="add(5)"/></td><td><input type="button" value="6" onclick="add(6)"/></td><td><input type="button" value="*" onclick="add('*')"/></td></tr><tr><td><input type="button" value="1" onclick="add(1)"/></td><td><input type="button" value="2" onclick="add(2)"/></td><td><input type="button" value="3" onclick="add(3)"/></td><td><input type="button" value="+" onclick="add('+')"/></td></tr><tr><td><input type="button" value="0" onclick="add(0)"/></td><td><input type="button" value="." onclick="add('.')"/></td><td><input type="button" value="=" onclick="computer()"/></td> <td><input type="button" value="-" onclick="add('-')"/></td></tr></table></BODY><script type="text/javascript">var flag=0;var array=new Array();var s;var t=document.getElementById('one');functioncle(){t.value='';}functionba(){if(t.value=='出错'){t.value='';return;}t.value=t.value.substring(0,t.value.length-1);}function add(n){if(n=='+'||n=='*'||n=='/'){if(t.value=='出错'){t.value='';}else if(t.value.length!=0){if(flag==1){flag=0;}var la=t.value.charAt(t.value.length-1);varbela=t.value.charAt(t.value.length-2);if(bela=='*'&&la=='-'){t.value=t.value.substring(0,t.value.length-2)+n;}else if(bela=='/'&&la=='-'){t.value=t.value.substring(0,t.value.length-2)+n;}else{if(la=='+'||la=='-'||la=='*'||la=='/'){t.value=t.value.substring(0,t.value.length-1)+n;}else{t.value=t.value+n;}}}}else if(n=='-'){if(t.value=='出错'){t.value='';}flag=0;var la=t.value.charAt(t.value.length-1);if(la!='-'){if(la=='+'){t.value=t.value.substring(0,t.value.length-1)+n;}else{t.value=t.value+n;}}}else if(n=='.'){if(flag==1){t.value='';flag=0;}array=t.value.split('+');s=array[array.length-1];array=s.split('-');s=array[array.length-1];array=s.split('*');s=array[array.length-1];array=s.split('/');s=array[array.length-1];if(s.indexOf('.')==-1){t.value=t.value+n;}}else{if(flag==1){t.value='';flag=0;}t.value=t.value+n;}}function computer(){flag=1;var ne=t.value;if(ne==''){}if(ne=='出错'){t.value='';return;}if(ne=='-'){t.value='出错';return;}if(ne.charAt(0)=='-')ne='0'+ne;var la=t.value.charAt(t.value.length-1);varbela=t.value.charAt(t.value.length-2);if(la=='-'){if(bela=='*'||bela=='/'){ne=ne.substring(0,ne.length-2);}else{ne=ne.substring(0,ne.length-1);}}else if(la=='*'||la=='/'||la=='+'){ne=ne.substring(0,ne.length-1);}t.value=jisuan(ne);}functionjisuan(ne){var one=ne.indexOf('*');var two=ne.indexOf('/');var three=ne.indexOf('+');var four=ne.indexOf('-',1);if(one==-1&&two==-1&&three==-1&&four==-1) returnparseFloat(ne);//第一个是*if(one!=-1&&(two==-1||one<two)){//*的前一个数var num1='';for(vari=one-1;i>=0;i--){varcb=ne.charAt(i);if(cb=='+'||cb=='-')num1+=cb;}var num11='';for(vari=num1.length-1;i>=0;i--){num11+=num1.charAt(i);}//*的后一个数var num2=ne.charAt(one+1);for(vari=one+2;i<ne.length;i++){varca=ne.charAt(i);if(ca=='+'||ca=='-'||ca=='*'||ca=='/')break;num2+=ca;}var sum=parseFloat(num11)*parseFloat(num2);varne1=''+ne.substring(0,one-num11.length)+sum+ne.substring(one+1+num2.length,ne.length);returnjisuan(ne1);}//第一个是/if(two!=-1&&(one==-1||one>two)){// /的前一个数var num1='';for(vari=two-1;i>=0;i--){varcb=ne.charAt(i);if(cb=='+'||cb=='-')break;num1+=cb;}//反转得到真正的前一个数var num11='';for(vari=num1.length-1;i>=0;i--){num11+=num1.charAt(i);}// /的后一个数var num2=ne.charAt(two+1);for(vari=two+2;i<ne.length;i++){varca=ne.charAt(i);if(ca=='+'||ca=='-'||ca=='*'||ca=='/')break;num2+=ca;}var sum=parseFloat(num11)/parseFloat(num2);varne1=''+ne.substring(0,two-num11.length)+sum+ne.substring(two+1+num2.length,ne.length);returnjisuan(ne1);}//第一个是+if(three!=-1&&(four==-1||three<four)){// +的前一个数var num1='';for(vari=three-1;i>=0;i--){varcb=ne.charAt(i);num1+=cb;}//反转得到真正的前一个数var num11='';for(vari=num1.length-1;i>=0;i--){num11+=num1.charAt(i);}// +的后一个数var num2=ne.charAt(three+1);for(vari=three+2;i<ne.length;i++){varca=ne.charAt(i);if(ca=='+'||ca=='-')break;num2+=ca;}var sum=parseFloat(num11)+parseFloat(num2);var ne1=''+sum+ne.substring(three+1+num2.length,ne.length);returnjisuan(ne1);}//第一个是-if(four!=-1&&(three==-1||three>four)){// -的前一个数var num1='';for(vari=four-1;i>=0;i--){varcb=ne.charAt(i);num1+=cb;}//反转得到真正的前一个数var num11='';for(vari=num1.length-1;i>=0;i--){num11+=num1.charAt(i);}// -的后一个数var num2=ne.charAt(four+1);for(vari=four+2;i<ne.length;i++){varca=ne.charAt(i);if(ca=='+'||ca=='-')break;num2+=ca;}var sum=parseFloat(num11)-parseFloat(num2);var ne1=''+sum+ne.substring(four+1+num2.length,ne.length);returnjisuan(ne1);}}</script></HTML>。
JavaScript实例--实现计算器
JavaScript实例--实现计算器⽬录⼀、实例代码⼆、实例演⽰三、实例剖析⼀、实例代码HTML:<!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>Document</title><style>/* Basic Reset */</style></head><body><div class="center"><h1>计算器</h1><a href="https:///guuibayer/simple-calculator" rel="external nofollow" target="_blank"><i class="fa fa-github"></i></a> <form name="calculator"><input type="button" id="clear" class="btn other" value="C"><input type="text" id="display"><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 operator" value="." onclick="get(this.value);"><input type="button" class="btn operator" value="/" onclick="get(this.value);"><input type="button" class="btn other" value="=" onclick="calculates();"></form></div><script></script></body></html>CSS:* {border: none;/*去除默认边框*/font-family: 'Open Sans', sans-serif;/*更改字体*/margin: 0;/*去除默认外边距*/padding: 0;/*去除默认内边距*/}.center {background-color: #fff;border-radius: 50%;/*圆⾓*/height: 600px;/*计算器总⾼度*/margin: auto;/*⽔平居中*/width: 600px;/*宽度*/}h1 {/*修改标题样式*/color: #495678;/*字体颜⾊*/font-size: 30px; /*字体⼤⼩*/margin-top: 20px;/*顶部外边距*/padding-top: 50px;/*顶部内边距*/display: block;/*修改为块级元素,独占⼀⾏*/text-align: center;/*⽂字居中*/text-decoration: none;/*去除默认⽂字样式*/}a {/*这是标题下⾯⼀块位置,点击可以跳转到github的仓库地址*/color: #495678;font-size: 30px;display: block;text-align: center;text-decoration: none;padding-top: 20px;}form {/*定义表单区域的样式*/background-color: #495678;/*背景颜⾊*/box-shadow: 4px 4px #3d4a65;/*阴影*/margin: 40px auto;/*定义外边距*/padding: 40px 0 30px 40px; /*定义内边距*/width: 280px;/*宽度*//*⾼度由内容撑起*/}.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;/*第⼀个按钮特殊*/}.btn, #display, form {/*按钮,⽂本输⼊框和整个表单区域*/border-radius: 25px;/*圆⾓*/}/*定义输⼊框*/#display {outline: none;/*清除默认边框样式*/background-color: #98d1dc;/*背景颜⾊*/box-shadow: inset 6px 6px 0px #3facc0;/*阴影*/color: #dededc;/*内部⽂本颜⾊*/font-size: 20px;/*⽂本⼤⼩*/height: 47px;/*输⼊框⾼度*/text-align: right;/*⽂本右对齐*/width: 165px;/*定义宽度*/padding-right: 10px;/*右内边距*/margin-left: 10px;/*左外边距*/}.number {/*定义数字的按钮*/background-color: #72778b;/*背景颜⾊*/box-shadow: 0 5px #5f6680;/*阴影*/color: #dededc;/*数字颜⾊*/}.number:active {/*选中数字样式,就是点击数字的动态效果*/box-shadow: 0 2px #5f6680;-webkit-transform: translateY(2px);-ms-transform: translateY(2px);-moz-tranform: translateY(2px);transform: translateY(2px);/*这四个其实是⼀样的,这是为了兼容不同的浏览器,效果就是向上移动2px距离需要配合js,点击时赋active,点击后抹掉*/}.operator {/*定义运算符按钮*/background-color: #dededc;/*背景颜⾊*/box-shadow: 0 5px #bebebe;/*阴影*/color: #72778b;/*运算符颜⾊*/}.operator:active {/*定义运算符点击时*//*这个⽐数字点击多了⼀个,就是把下⾯的阴影减少了⼀点*/box-shadow: 0 2px #bebebe;-webkit-transform: translateY(2px);-ms-transform: translateY(2px);-moz-tranform: translateY(2px);transform: translateY(2px);}.other {/*定义归零键和=键*/background-color: #e3844c;/*背景颜⾊*/box-shadow: 0 5px #e76a3d;/*阴影*/color: #dededc;/*符号颜⾊*/}.other:active {/*点击效果和点击运算符⼀样*/box-shadow: 0 2px #e76a3d;-webkit-transform: translateY(2px);-ms-transform: translateY(2px);-moz-tranform: translateY(2px);transform: translateY(2px);}JavaScript:/* limpa o display */document.getElementById("clear").addEventListener("click", function() {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);};⼆、实例演⽰页⾯加载后,显⽰⼀个计算器的页⾯,可以进⾏正常的四则运算运算结果:也可以归零,加⼩数等等操作三、实例剖析⽅法解析document.getElementById("display").value = eval(result);eval() 函数计算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是一种广泛用于网页开发的脚本语言,可以方便地与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中实现一个简单的计算器并不困难,我们只需利用基本的数学运算符和JavaScript的语法即可。
下面是一个实现加、减、乘、除四则运算的计算器的JavaScript代码示例:```javascript// 获取计算器的元素var calculator = document.getElementById('calculator'); // 获取数字、运算符和结果显示区域的元素var num1 = document.getElementById('num1');var num2 = document.getElementById('num2');var operator = document.getElementById('operator');var result = document.getElementById('result');// 给运算符按钮添加事件处理函数var addButton = document.getElementById('add');addButton.addEventListener('click', function() {var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 + n2;});var subtractButton =document.getElementById('subtract');subtractButton.addEventListener('click', function() {var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 - n2;});var multiplyButton =document.getElementById('multiply');multiplyButton.addEventListener('click', function() { var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 * n2;});var divideButton = document.getElementById('divide'); divideButton.addEventListener('click', function() {var n1 = parseFloat(num1.value);var n2 = parseFloat(num2.value);result.innerHTML = n1 / n2;});```在以上代码中,我们定义了四个函数来处理加、减、乘、除四则运算。
JS快速实现简单计算器
JS快速实现简单计算器本⽂实例为⼤家分享了JS实现简单计算器的具体代码,供⼤家参考,具体内容如下直接上图HTML部分<!DOCTYPE html><html><head><meta charset="UTF-8"><title>我的第⼀个计算器</title><link rel="stylesheet" href="计算器.css" rel="external nofollow" /><script src="计算器.js"></script></head><body><h1 style="text-align: center;">欢迎使⽤</h1><!--<audio src="audio/1.mp3" id="music"></audio>--><hr /><p style="text-align: center;color:#6495ED;">输⼊不要超过8位数哦</p><div class="box"><div class="header"><div class="screen"><b id="s1"></b></div><div class="screen"><b id="s2"></b></div></div><div class="content"><input type="button" name="" id="start" value="开始" /><input type="button" name="" id="clear" value="清零" /><input type="button" name="" id="del" value="删除" /><input type="button" name="" id="stop" value="关闭" /><input type="button" name="" id="b1" value="1" /><input type="button" name="" id="b2" value="2" /><input type="button" name="" id="b3" value="3" /><input type="button" name="" id="b+" value="+" /><input type="button" name="" id="b4" value="4" /><input type="button" name="" id="b5" value="5" /><input type="button" name="" id="b6" value="6" /><input type="button" name="" id="b-" value="-" /><input type="button" name="" id="b7" value="7" /><input type="button" name="" id="b8" value="8" /><input type="button" name="" id="b9" value="9" /><input type="button" name="" id="bx" value="*" /><input type="button" name="" id="b0" value="0" /><input type="button" name="" id="b." value="." /><input type="button" name="" id="b=" value="=" /><input type="button" name="" id="b÷" value="÷" /><span style="line-height: 30px;">制作⼈:xxx 监督⼈:xxx</span></div></div></body></html>CSS部分* {margin: 0px;padding: 0px;}/*body {background: cornflowerblue;}*/.box {width: 260px;height: 330px;border: 5px solid cornflowerblue;margin: 60px auto;border-radius: 10px;}.header {width: 260px;height: 80px;background:lightcyan;}.screen {width: 260px;height: 40px;background:lightcyan;font-size: 25px;text-align: center;}.content {width: 260px;height: 250px;color: yellowgreen;background: #FAEBD7;text-align: center;}input {text-align: center;width: 60px;height: 40px;background: pink;margin-top: 4px;font-size: 15px;}b {color: fuchsia;}JS部分window.onload = function() {function $(id) {return document.getElementById(id);}function put1(id){$(id).onclick = function() {$("s1").innerHTML = $("s1").innerHTML+this.value; if ($("s1").innerHTML==116) {prompt("你爱我吗");$("s1").innerHTML = "嘻嘻"}if ($("s1").innerHTML==1129) {alert("我爱你");}if ($("s1").innerHTML==1314520) {alert("我爱你");}}}var result;$("b=").onclick = function() {result = eval($("s1").innerHTML);$("s2").innerHTML = "="+result;}$("start").onclick = function() {$("s1").innerHTML = "欢迎使⽤";$("s2").innerHTML = "使⽤前清零";$("music").play();}$("clear").onclick = function() {$("s1").innerHTML = "";$("s2").innerHTML = "";}$("stop").onclick = function() {$("s1").innerHTML = "再见";setTimeout(function() {$("s1").innerHTML = "";$("s2").innerHTML = "";},3000);$("music").pause();}$("del").onclick = function() {$("s1").innerHTML = $("s1").innerHTML.substr(0, $("s1").innerHTML.length - 1);}put1("b1");put1("b2");put1("b3");put1("b4");put1("b5");put1("b6");put1("b7");put1("b8");put1("b9");put1("b0");put1("b+");put1("b-");put1("bx");put1("b÷");put1("b.");}更多计算器功能实现,请点击专题:进⾏学习以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。
用js写一个简易计算器
⽤js写⼀个简易计算器要求1.实现最基本的+ - * / %运算,样式不做要求。
2.有⼀个【清除】按钮,清除所有输⼊有⼏个地⽅需要注意:如何获取输⼊框的内容?//⽤H5的⽅法获取元素内容var n1 = document.querySelector('.n1');var n2 = document.querySelector('.n2');如何取得运算符的内容?1.先获取select这个下拉框var ys = document.querySelector('#ys');2.然后获取被选中的下标值,并获取到该值(运算符)var index = ys.selectedIndex;var opt = ys.options[index].value;获取到的内容能否直接运算?有了两个值和运算符,还不能直接元素。
因为获取到的内容都是string字符串类型。
需要强制转换成number类型。
然后⽤switch语句判断运算符内容,并进⾏对应的运算。
如何把运算结果写到页⾯中?⾸页要获取到展⽰结果的位置获取元素⽂本内容,有⼏种⽅式:1.innerHTML或者innerContextinnerHTML会读取内容的语义,解析标签innerContext和上⾯作⽤⼀样,只适⽤于⽕狐(Firefox)浏览器。
2.innerText(推荐使⽤)只是读取直接⼦级的⽂字2.textContent (不推荐使⽤)读取的内容不仅仅是直接⼦级,元素所有的⽂字内容也会被读取出,不推荐使⽤,会被恶意注⼊。
清除按钮怎么清除所有内容?上⾯功能完成了,⼏乎就没啥问题了。
清除就是把所有的输⼊框,结果对应的元素标签element.innerText = '';<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>计算器</title><style>input,select,option,span,p,button{width: 80px;height: 30px;font-size: 20px;}.clear{cursor: pointer;border: 1px solid #333;}p.result{display: inline-block;min-width: 50px;width: 150px;}option{font-size: 26px;}</style></head><body><input type="number" value="" class="n1"><select id="ys"><option value="+">+</option><option value="-">-</option><option value="*">*</option><option value="/">/</option><option value="%">%</option></select><input type="number" class="n2" value=""><button>=</button><p class="result">0</p><br><span class="clear">清除</span><script>var n1 = document.querySelector(".n1");var n2 = document.querySelector(".n2");var ys = document.querySelector("#ys");var result = document.querySelector(".result");var btn = document.querySelector("button");var clear = document.querySelector(".clear")//点击按钮计算结果btn.onclick= function(){var resultValue;switch(ys.value){case '+':resultValue = parseFloat(n1.value)+parseFloat(n2.value);break;case '-':resultValue = parseFloat(n1.value)-parseFloat(n2.value);break;case '*':resultValue = parseFloat(n1.value)*parseFloat(n2.value);break;case '/':resultValue = parseFloat(n1.value) / parseFloat(n2.value);break;case '%':resultValue = parseInt(n1.value) % parseInt(n2.value);}//解决不同浏览器对innerText属性兼容性问题, firefox⽤的是innerContent(typeof result.innerText) == "string" ? (result.innerText = resultValue) : (result.innerContent = resultValue) ; }//清零clear.onclick = function(){result.innerText = '0';n1.value = '';n2.value = '';}</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实现四则运算计算器
简单js实现计算器<html><head><script>function addnumber(){var num1=parseFloat(document.form1.num1.value); var num2=parseFloat(document.form1.num2.value); var num;num=(num1+num2);document.form1.num.value=num;}function jiannumber(){var num1=parseFloat(document.form1.num1.value); var num2=parseFloat(document.form1.num2.value); var num;num=(num1-num2);document.form1.num.value=num;}function chennumber(){var num1=parseFloat(document.form1.num1.value); var num2=parseFloat(document.form1.num2.value); var num;num=(num1*num2);document.form1.num.value=num;}function chunumber(){var num1=parseFloat(document.form1.num1.value); var num2=parseFloat(document.form1.num2.value); var num;num=(num1/num2);document.form1.num.value=num;}</script></head><body><form name="form1"><input type="text" name="num1" /><input type="button" name="addnum" value="+" onclick="addnumber()" /> <input type="button" name="jiannum" value="-" onclick="jiannumber()" /><input type="button" name="chennum" value="*"onclick="chennumber()" /> <input type="button" name="chunum" value="/" onclick="chunumber()" /> <input type="text" name="num2"> =<input type="text" name="num"></form></body></html>。
原生javascript开发计算器实例
原⽣javascript开发计算器实例计算器的主要作⽤是进⾏数字运算,开发⼀个计算器功能的web实例,有助于更好的掌握js基础的数字运算能⼒。
本实例详细分析⼀个js计算器的开发步骤,学习本教程时最好先具备⼀些基础的js知识。
计算器包括显⽰数字区域和按键区域两⼤部分,先把计算器的这两个区域的html元素编写出来,如下所⽰:<div class="calculator_wrap" id="calculator"><!--计算器外包元素--><div class="show_num"><!--显⽰数字区域--><div class="num_save" id="numSave"></div><!--计算公式--><div class="num_cur" id="numCur">0</div><!--计算结果--><div class="show_m" id="showM">M</div><!--记忆存储标志--></div><div class="btn_wrap" id="btnWrap"><!--按钮区域--><div class="btn" data-key="MC">MC</div><!--记忆清零--><div class="btn" data-key="MR">MR</div><!--记忆读取--><div class="btn" data-key="MS">MS</div><!--存储记忆--><div class="btn" data-key="MA">M+</div><!--记忆加--><div class="btn" data-key="ML">M-</div><!--记忆减--><div class="btn" data-key="BACK">←</div><!--退格--><div class="btn" data-key="CE">CE</div><!--清除当前--><div class="btn" data-key="Clear">C</div><!--清除--><div class="btn" data-key="Negate">±</div><!--正负转换--><div class="btn" data-key="Square">√ ̄</div><!--平⽅根--><div class="btn" data-key="Num" data-value="7">7</div><!--7--><div class="btn" data-key="Num" data-value="8">8</div><!--8--><div class="btn" data-key="Num" data-value="9">9</div><!--9--><div class="btn" data-key="Base" data-value="/">/</div><!--除--><div class="btn" data-key="Percentage">%</div><!--百分号--><div class="btn" data-key="Num" data-value="4">4</div><!--4--><div class="btn" data-key="Num" data-value="5">5</div><!--5--><div class="btn" data-key="Num" data-value="6">6</div><!--6--><div class="btn" data-key="Base" data-value="*">*</div><!--乘--><div class="btn" data-key="Reciprocal">1/x</div><!--倒数--><div class="btn" data-key="Num" data-value="1">1</div><!--1--><div class="btn" data-key="Num" data-value="2">2</div><!--2--><div class="btn" data-key="Num" data-value="3">3</div><!--3--><div class="btn" data-key="Base" data-value="-">-</div><!--减--><div class="btn equal" data-key="Equal">=</div><!--等于--><div class="btn zero" data-key="Num" data-value="0">0</div><!--0--><div class="btn" data-key="Point">.</div><!--⼩数点--><div class="btn" data-key="Base" data-value="+">+</div><!--加--></div></div>读者可以⾃⼰编写⼀些样式,设计⼀个⾃⼰喜欢的计算器效果。
JS实现计算器带三角函数根号
JS实现计算器带三角函数根号以下是一个使用JavaScript实现的计算器代码,它包含了三角函数、开方等功能。
总字数超过1200字,但是实际代码量并不多,请自行补充。
```javascript//获取页面元素const display = document.getElementById("display");const buttons = document.getElementsByClassName("btn");//绑定按钮事件for (let i = 0; i < buttons.length; i++)buttons[i].addEventListener("click", buttonClick);//按钮点击事件处理函数function buttonClick(event)const buttonValue = event.target.innerHTML;if (buttonValue === "=")calculate(;} else if (buttonValue === "C")clear(;} else if (buttonValue === "√")squareRoot(;} else if (buttonValue === "sin")sine(;} else if (buttonValue === "cos")cosine(;} elseappendValue(buttonValue);}//向显示屏追加内容function appendValue(value)display.value += value;//清空显示屏function cleadisplay.value = "";//计算结果function calculattryconst result = eval(display.value); // 使用eval计算表达式display.value = result.toFixed(4); // 结果四舍五入保留4位小数} catch (error)display.value = "Error";}//计算平方根function squareRootryconst result = Math.sqrt(eval(display.value));display.value = result.toFixed(4);} catch (error)display.value = "Error";}//计算正弦值function sintryconst result = Math.sin(eval(display.value) * (Math.PI / 180)); // 将角度转换为弧度display.value = result.toFixed(4);} catch (error)display.value = "Error";}//计算余弦值function cosintryconst result = Math.cos(eval(display.value) * (Math.PI / 180)); // 将角度转换为弧度display.value = result.toFixed(4);} catch (error)display.value = "Error";}```HTML部分:```html<!DOCTYPE html><html><head><title>Calculator</title><link rel="stylesheet" type="text/css" href="style.css"> </head><body><div id="calculator"><input type="text" id="display" readonly> <div id="buttons"><div class="row"><button class="btn">7</button><button class="btn">8</button><button class="btn">9</button><button class="btn">/</button></div><div class="row"><button class="btn">4</button><button class="btn">5</button><button class="btn">6</button><button class="btn">*</button></div><div class="row"><button class="btn">1</button><button class="btn">2</button><button class="btn">3</button><button class="btn">-</button></div><div class="row"><button class="btn">0</button><button class="btn">.</button><button class="btn">+</button><button class="btn">=</button></div><div class="row"><button class="btn">C</button><button class="btn">√</button> <button class="btn">sin</button> <button class="btn">cos</button> </div></div></div><script src="script.js"></script> </body></html>```CSS部分:```css#calculatorwidth: 200px;margin: 0 auto;padding: 20px;#displaywidth: 100%;margin-bottom: 10px;padding: 5px;font-size: 20px;.rowdisplay: flex;.buttonflex: 1;margin-right: 5px;padding: 10px;font-size: 16px;```请注意,这只是一个简单的示例,实际的计算器功能可能更加复杂,需要根据具体需求进行适当的修改和扩展。
JS实现计算器,带三角函数,根号
JS实现计算器,带三⾓函数,根号极简主义⽹页计算器。
实现了按键特效,可响应键盘按键,实时显⽰计算结果。
可切换模式,拓展⾼级功能,包括根号、三⾓函数、括号等。
效果如下:代码如下:html:<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><title>Calculator</title><link rel="stylesheet" href="css/main.css"><link rel="stylesheet" href="css/reset.css"><script src='js/main.js' type='text/javascript'></script></head><body onkeypress="keyboard();"><div id="calculator"><!--计算器主体框架--><div class="setting"><!--计算器标头--><p class="head">Calculator</p></div><div class="display"><!--显⽰界⾯--><input type="text" id="exp" class="expression" disabled> <!--表达式区域--><input type="text" id="ans" class="answer" disabled><!--答案区域--></div><div class="keyboard"><!--键盘--><ul><li onclick="model()">M</li><li onclick="append('C')">C</li><li onclick="append('B')">B</li><li onclick="append('/')">/</li><li onclick="append(1)">1</li><li onclick="append(2)">2</li><li onclick="append(3)">3</li><li onclick="append('*')">×</li><li onclick="append(4)">4</li><li onclick="append(5)">5</li><li onclick="append(6)">6</li><li onclick="append('-')">-</li><li onclick="append(7)">7</li><li onclick="append(8)">8</li><li onclick="append(9)">9</li><li onclick="append('+')">+</li><li onclick="append('.')">.</li><li onclick="append(0)"></li><li onclick="plus_min();">±</li><li onclick="append('=')">=</li></ul></div></div><div id="expand"><ul><li onclick="Sqrt();">√</li><li onclick="append('(')">(</li><li onclick="append(')')">)</li><li onclick="append('sin(')">sin</li><li onclick="append('cos(')">cos</li></ul></div></body></html><!--Made by Vincent Zhang 2017/07/10--> Css:main.cssbody {text-align: center;-webkit-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;}#calculator {position: relative;border: 2px solid black;width: 320px;height: 590px;top: 20px;margin: 0 auto;}.setting {position: relative;width: 100%;height: 40px;border: 0px solid black;margin: 0 auto;}.head {float: left;margin: 0;padding-left: 17px;line-height: 40px;}.display {position: relative;width: 100%;height: 200px;border: 0px solid black;margin: 0 auto;}.expression {float: left;margin: 0;padding: 0;position: relative;width: 93%;height: 70px;border: 0px solid black;margin: 0 auto;text-align: right;font-size: 30px;color: #000;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;border: 0;outline: none;background-color: #FFFFFF; }.answer {float: left;margin: 0;padding: 0;position: relative;width: 93%;height: 130px;border: 0px solid black;margin: 0 auto;text-align: right;font-size: 50px;color: #000;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;border: 0;outline: none;background-color: #FFFFFF; }.keyboard {padding: 0;position: relative;float: right;width: 320px;height: 343px;border: 0px solid black;margin: 0 auto;}ul {list-style: none;padding: 0;margin: 0;}ul li {float: left;display: block;width: 80px;height: 68px;line-height: 68px;padding: 0;margin: 0;text-decoration: none;color: #000;display: block;cursor: pointer;}ul li:hover {color: #000000;background-color: rgb(230, 230, 230);}#expand {position: absolute;border: 0px solid black;width: 80px;height: 340px;padding: 0;margin: 0;display: none;}reset,css/*! normalize.css v7.0.0 | MIT License | /necolas/normalize.css *//* Document========================================================================== */ /*** 1. Correct the line height in all browsers.* 2. Prevent adjustments of font size after orientation changes in* IE on Windows Phone and in iOS.*/html {line-height: 1.15;/* 1 */-ms-text-size-adjust: 100%;/* 2 */-webkit-text-size-adjust: 100%;/* 2 */}/* Sections========================================================================== */ /*** Remove the margin in all browsers (opinionated).*/body {margin: 0;/*** Add the correct display in IE 9-.*/article,aside,footer,header,nav,section {display: block;}/*** Correct the font size and margin on `h1` elements within `section` and* `article` contexts in Chrome, Firefox, and Safari.*/h1 {font-size: 2em;margin: 0.67em 0;}/* Grouping content========================================================================== */ /*** Add the correct display in IE 9-.* 1. Add the correct display in IE.*/figcaption,figure,main {/* 1 */display: block;}/*** Add the correct margin in IE 8.*/figure {margin: 1em 40px;}/*** 1. Add the correct box sizing in Firefox.* 2. Show the overflow in Edge and IE.*/hr {box-sizing: content-box;/* 1 */height: 0;/* 1 */overflow: visible;/* 2 */}/*** 1. Correct the inheritance and scaling of font size in all browsers.* 2. Correct the odd `em` font sizing in all browsers.*/pre {font-family: monospace, monospace;/* 1 */font-size: 1em;/* 2 *//* Text-level semantics========================================================================== */ /*** 1. Remove the gray background on active links in IE 10.* 2. Remove gaps in links underline in iOS 8+ and Safari 8+.*/a {background-color: transparent;/* 1 */-webkit-text-decoration-skip: objects;/* 2 */}/*** 1. Remove the bottom border in Chrome 57- and Firefox 39-.* 2. Add the correct text decoration in Chrome, Edge, IE, Opera, and Safari.*/abbr[title] {border-bottom: none;/* 1 */text-decoration: underline;/* 2 */text-decoration: underline dotted;/* 2 */}/*** Prevent the duplicate application of `bolder` by the next rule in Safari 6.*/b,strong {font-weight: inherit;}/*** Add the correct font weight in Chrome, Edge, and Safari.*/b,strong {font-weight: bolder;}/*** 1. Correct the inheritance and scaling of font size in all browsers.* 2. Correct the odd `em` font sizing in all browsers.*/code,kbd,samp {font-family: monospace, monospace;/* 1 */font-size: 1em;/* 2 */}/*** Add the correct font style in Android 4.3-.*/dfn {font-style: italic;}* Add the correct background and color in IE 9-.*/mark {background-color: #ff0;color: #000;}/*** Add the correct font size in all browsers.*/small {font-size: 80%;}/*** Prevent `sub` and `sup` elements from affecting the line height in* all browsers.*/sub,sup {font-size: 75%;line-height: 0;position: relative;vertical-align: baseline;}sub {bottom: -0.25em;}sup {top: -0.5em;}/* Embedded content========================================================================== */ /*** Add the correct display in IE 9-.*/audio,video {display: inline-block;}/*** Add the correct display in iOS 4-7.*/audio:not([controls]) {display: none;height: 0;}/*** Remove the border on images inside links in IE 10-.*/img {border-style: none;}/*** Hide the overflow in IE.*/svg:not(:root) {}/* Forms========================================================================== */ /*** 1. Change the font styles in all browsers (opinionated).* 2. Remove the margin in Firefox and Safari.*/button,input,optgroup,select,textarea {font-family: sans-serif;/* 1 */font-size: 100%;/* 1 */line-height: 1.15;/* 1 */margin: 0;/* 2 */}/*** Show the overflow in IE.* 1. Show the overflow in Edge.*/button,input {/* 1 */overflow: visible;}/*** Remove the inheritance of text transform in Edge, Firefox, and IE.* 1. Remove the inheritance of text transform in Firefox.*/button,select {/* 1 */text-transform: none;}/*** 1. Prevent a WebKit bug where (2) destroys native `audio` and `video`* controls in Android 4.* 2. Correct the inability to style clickable types in iOS and Safari.*/button,html [type="button"],/* 1 */[type="reset"],[type="submit"] {-webkit-appearance: button;/* 2 */}/*** Remove the inner border and padding in Firefox.*/button::-moz-focus-inner,[type="button"]::-moz-focus-inner,[type="reset"]::-moz-focus-inner,[type="submit"]::-moz-focus-inner {padding: 0;}/*** Restore the focus styles unset by the previous rule.*/button:-moz-focusring,[type="button"]:-moz-focusring,[type="reset"]:-moz-focusring,[type="submit"]:-moz-focusring {outline: 1px dotted ButtonText;}/*** Correct the padding in Firefox.*/fieldset {padding: 0.35em 0.75em 0.625em;}/*** 1. Correct the text wrapping in Edge and IE.* 2. Correct the color inheritance from `fieldset` elements in IE.* 3. Remove the padding so developers are not caught out when they zero out * `fieldset` elements in all browsers.*/legend {box-sizing: border-box;/* 1 */color: inherit;/* 2 */display: table;/* 1 */max-width: 100%;/* 1 */padding: 0;/* 3 */white-space: normal;/* 1 */}/*** 1. Add the correct display in IE 9-.* 2. Add the correct vertical alignment in Chrome, Firefox, and Opera.*/progress {display: inline-block;/* 1 */vertical-align: baseline;/* 2 */}/*** Remove the default vertical scrollbar in IE.*/textarea {overflow: auto;}/*** 1. Add the correct box sizing in IE 10-.* 2. Remove the padding in IE 10-.*/[type="checkbox"],[type="radio"] {box-sizing: border-box;padding: 0;/* 2 */}/*** Correct the cursor style of increment and decrement buttons in Chrome.*/[type="number"]::-webkit-inner-spin-button,[type="number"]::-webkit-outer-spin-button {height: auto;}/*** 1. Correct the odd appearance in Chrome and Safari.* 2. Correct the outline style in Safari.*/[type="search"] {-webkit-appearance: textfield;/* 1 */outline-offset: -2px;/* 2 */}/*** Remove the inner padding and cancel buttons in Chrome and Safari on macOS.*/[type="search"]::-webkit-search-cancel-button,[type="search"]::-webkit-search-decoration {-webkit-appearance: none;}/*** 1. Correct the inability to style clickable types in iOS and Safari.* 2. Change font properties to `inherit` in Safari.*/::-webkit-file-upload-button {-webkit-appearance: button;/* 1 */font: inherit;/* 2 */}/* Interactive========================================================================== */ /** Add the correct display in IE 9-.* 1. Add the correct display in Edge, IE, and Firefox.*/details,/* 1 */menu {display: block;}/** Add the correct display in all browsers.*/summary {display: list-item;}========================================================================== */ /*** Add the correct display in IE 9-.*/canvas {display: inline-block;}/*** Add the correct display in IE.*/template {display: none;}/* Hidden========================================================================== */ /*** Add the correct display in IE 10-.*/[hidden] {display: none;}JS:var modelFlag = 0;function append(str) {if (str == 'C') {exp.value = "";ans.value = "";} else if (str == 'B') {cstr = String(exp.value);cstr = cstr.substring(0, cstr.length - 1);exp.value = cstr;if (exp.value.length != 0)caculate();elseans.value = "";} else if (str == '=') {caculate();} else {exp.value += str;caculate();}}function plus_min() {cstr = String(exp.value);if (cstr[0] == '-') {cstr = cstr.substring(1, cstr.length);exp.value = cstr;caculate();} else {cstr = "-" + cstr;exp.value = cstr;caculate();}}function caculate() {expStr = String(exp.value);while (expStr.search(/sin\((\S*)\)/) != -1) {contant = expStr.match(/sin\(([^\)]*)\)/);expStr = expStr.replace(contant[0], String(Math.sin(parseFloat(contant[1]) / 180 * Math.PI))); }while (expStr.search(/cos\((\S*)\)/) != -1) {contant = expStr.match(/cos\(([^\)]*)\)/);expStr = expStr.replace(contant[0], String(Math.cos(parseFloat(contant[1]) / 180 * Math.PI)));}if (expStr.length == 0) {ans.value = "0";} else {ans.value = eval(expStr);}}function keyboard() {key = window.event.keyCode;if (key >= 45 && key <= 57) {append(String.fromCharCode(key));} else if (key >= 40 && key <= 43) {append(String.fromCharCode(key));} else if (key == 13) {caculate();} else if (key == 8) {append('B');}}function model() {if (modelFlag == 0) {document.getElementById("calculator").style.width = "400px";document.getElementById("expand").style.top = String(document.getElementById("calculator").offsetTop + 242) + "px"; document.getElementById("expand").style.left = String(document.getElementById("calculator").offsetLeft + 2) + "px"; document.getElementById("expand").style.display = "block";modelFlag = 1;} else {document.getElementById("expand").style.display = "none";document.getElementById("calculator").style.width = "320px";modelFlag = 0;}}function Sqrt() {if (ans.value > 0) {ans.value = Math.sqrt(ans.value);exp.value = "";} else {ans.value = "Erro";exp.value = "";}}如果对你有所帮助,亲点个推荐和关注,谢谢。
网页计算器--JS代码
网页计算器的界面:该计算其代码如下:<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head id="Head1" runat="server"><title>网页计算器</title></head><script type="text/javascript">var t;t = self.setInterval("ShowTime()", 10);var Exp = "";function ShowTime() {var Today = new Date(); //这条语句要放在该函数内,而不能作为全局变量hours = Today.getHours(); minutes = Today.getMinutes(); second = Today.getSeconds();if (hours < 10) hours = "0" + hoursif (minutes < 10) minutes = "0" + minutesif (second < 10) second = "0" + seconddocument.all.time.value = hours + ":" + minutes + ":" + second;}function MyFun() {alert(Exp);}//获取光标在ID为obj控件的位置,返回下标function getPos(obj) {obj.focus();var s = document.selection.createRange();s.setEndPoint("StartToStart", obj.createTextRange())return s.text.length;}//设置光标位置的函数function setCursor(ctrl, pos){if(ctrl.setSelectionRange){ctrl.focus();ctrl.setSelectionRange(pos,pos);}else if (ctrl.createTextRange){var range = ctrl.createTextRange();range.collapse(true);range.moveEnd('character', pos);range.moveStart('character', pos);range.select();}}//删除表达式中的元素function Delete() {var Len = document.all.In.value.length;Exp = document.all.In.value;var Arr = Exp.split("");var pos = getPos(In);Arr.splice(pos - 1, 1, "");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Exp = toStr;Arr = toStr.split("");document.all.In.value = toStr;setCursor(In,pos - 1);}//清除表达式function Clearn() {document.all.In.value = "";}function addParentheses(strObj) {var Temp = strObj;var Arr = Temp.split("");for (var i = 0; i < Arr.length; ++i) {if (Arr[i] == "s" || Arr[i] == "c" || Arr[i] == "t" || Arr[i] == "√"){if (Arr[i + 1] != "("){Arr.splice(i, 1, Arr[i] + "(");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Arr = toStr.split("");var Index = i + 2;if (Arr[Index] != "s" && Arr[Index] != "c" && Arr[Index] != "t" && Arr[Index] != "√"){var Bol = true;while (Bol) {if (Arr[Index + 1] == "+" || Arr[Index + 1] == "-" || Arr[Index + 1] == "*" || Arr[Index + 1] == "/" || Arr.length <= (Index + 1)){Arr.splice(Index, 1, Arr[Index] + ")");var toStr = "";for(var l = 0; l < Arr.length; ++l)toStr += Arr[l];Arr = toStr.split("");Bol = false;}++Index;}var S = "";for(var k = 0; k < Arr.length; ++k)S += Arr[k];S = Arr.toString();}//如果参数是函数else{var val = 0;var Bol = true;var hasPar = false;while (Bol){if (Arr[Index + 1] == "("){hasPar = true;val++;}if (Arr[Index + 1] == ")")--val;//没有括号的情况if (((Arr[Index + 1] == "+" || Arr[Index + 1] == "-" || Arr[Index + 1] == "*" || Arr[Index + 1] == "/") && !hasPar) || (Index + 1) >= Arr.length){Arr.splice(Index, 1, Arr[Index] + ")");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Arr = toStr.split("");Bol = false;}//有括号的情况if (val == 0 && hasPar){Arr.splice(Index + 1, 1,Arr[Index + 1] + ")");var toStr = "";for(var j = 0; j < Arr.length; ++j)toStr += Arr[j];Arr = toStr.split("");Bol = false;}++Index;}}}}var Str = "";for (var m = 0; m < Arr.length; ++m)Str += Arr[m];Exp = Str;}}//在表达式中添加表达式元素function addElement(Ele) {var Arr = new Array();Exp = document.all.In.value;var Index = getPos(In);if (Index >= Exp.length) {Exp += Ele;}else {Arr = Exp.split("");var Cha = Arr[Index];Arr.splice(Index, 1, Ele + Cha);var Str = "";for (var i = 0; i < Arr.length; ++i)Str += Arr[i];Exp = Str;}document.all.In.value = Exp;setCursor(In,Index + Ele.length);}function Input1() {addElement("1");}function Input2() {addElement("2");}function Input3() {addElement("3");}function Input4() {addElement("4");}function Input5() {addElement("5");}function Input6() {addElement("6");}function Input7() {addElement("7");}function Input8() {addElement("8");}function Input9() {addElement("9");}function Input0() {addElement("0");}function InputDot() {addElement(".");}function InputSin() {addElement("sin");}function InputCos() {addElement("cos");}function InputTan() {addElement("tan");}function InputSqtr() {addElement("√");}function InputAdd() {addElement("+");}function InputMin() {addElement("-");}function InputMult() {addElement("*");}function InputDiv() {addElement("/");}function InputPI() {addElement("3.141592"); }function InputLPar() {addElement("(");}function InputRPar() {addElement(")");}function InputLn() {addElement("ln");}function InputLog() {addElement("log");}function InputEql() {Exp = document.all.In.value;var Str = "";Str = Exp.replace(/sin/g, "s");Str = Str.replace(/cos/g, "c");Str = Str.replace(/tan/g, "t");addParentheses(Str);Exp = Exp.replace(/t/g, "Math.tan");Exp = Exp.replace(/s/g, "Math.sin");Exp = Exp.replace(/c/g, "Math.cos");Exp = Exp.replace(/√/g, "Math.sqrt");var result = eval(Exp);document.all.Restlt.value = result;}</script><body ><table border="8" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><label id = "Lab" ></label> 计算器</td></tr></table><table border="1" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><input id = "In" type = "text" style="width:160px" /></td><td><input id = "bs" type = "button" value = "Backspace" style="width:75px" onclick = "Delete();"/></td></tr></table><table border="1" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><input id = "Restlt" type = "text" style="width:110px" /></td><td><input id = "Clearn" type = "button" value = "Clearn" style="width:60px" onclick = "Clearn();" /></td><td><input id = "time" type = "text" style="width:60px" /></td></tr></table><table border="5" bgcolor="rgb(50,200,100)" align= "center" cellspacing="0" cellpadding="0", width="250pt"><tr><td><input type = "button" id = "N1" style="width:50px" value = "1" onclick = "Input1();"/></td><td><input type = "button" id = "N2" style="width:50px" value = "2" onclick = "Input2();" /></td><td><input type = "button" id = "N3" style="width:50px" value = "3" onclick = "Input3();" /></td><td><input type = "button" id = "Add" style="width:40px" value = "+" onclick ="InputAdd();" /></td><td><input type = "button" id = "Sub" style="width:40px" value = "-" onclick = "InputMin();"/></td></tr><tr><td><input type = "button" id = "N4" style="width:50px" value = "4" onclick = "Input4();"/></td><td><input type = "button" id = "N5" style="width:50px" value = "5" onclick = "Input5();" /></td><td><input type = "button" id = "N6" style="width:50px" value = "6" onclick = "Input6();" /></td><td><input type = "button" id = "Times" style="width:40px" value = "*" onclick = "InputMult();" /></td><td><input type = "button" id = "Divd" style="width:40px" value = "/" onclick = "InputDiv();" /></td></tr><tr><td><input type = "button" id = "N7" style="width:50px" value = "7" onclick = "Input7();"/></td><td><input type = "button" id = "N8" style="width:50px" value = "8" onclick = "Input8();" /></td><td><input type = "button" id = "N9" style="width:50px" value = "9" onclick = "Input9();" /></td><td><input type = "button" id = "Sqt" style="width:40px" value = "√" onclick = "InputSqtr();" /></td><td><input type = "button" id = "sin" style="width:40px" value = "sin" onclick = "InputSin();" /></td></tr><tr><td><input type = "button" id = "N0" style="width:50px" value = "0" onclick = "Input0();"/></td><td><input type = "button" id = "Dot" style="width:50px" value = "." onclick = "InputDot();" /></td><td><input type = "button" id = "Eql" style="width:50px" value = "=" onclick = "InputEql();" /></td><td><input type = "button" id = "cos" style="width:40px" value = "cos" onclick = "InputCos();" /></td><td><input type = "button" id = "tan" style="width:40px" value = "tan" onclick = "InputTan();" /></td></tr><tr><td><input type = "button" id = "PI" style="width:50px" value = "π" onclick = "InputPI();"/></td><td><input type = "button" id = "L_Par" style="width:50px" value = "(" onclick = "InputLPar();" /></td><td><input type = "button" id = "R_Par" style="width:50px" value = ")" onclick = "InputRPar();" /></td><td><input type = "button" id = "Ln" style="width:40px" value = "ln" onclick = "InputLn();" /></td><td><input type = "button" id = "Log" style="width:40px" value = "log" onclick = "InputLog();" /></td></tr></table><input id = "Input" type = "button" value = "click" onclick = "MyFun();" /> <form id="form1" runat="server"><div></div></form></body></html>。
用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,请⼤家提出来!)。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
<html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312"><title>一个计算器js脚本,sky整理收集。
</title><style><!--BODY {font-size: 12px;background-color: #d4d4d4;color: #0001fC;background-attachment: fixed;}td{font-size:12px; font-color:#000000}//--></style><script language="javascript"><!--var endNumber=truevar mem=0var carry=10var hexnum="0123456789abcdef"var angle="d"var stack=""var level="0"var layer=0//数字键function inputkey(key){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))))if(endNumber){endNumber=falsedocument.calc.display.value = key}else if(document.calc.display.value == null || document.calc.display.value == "0")document.calc.display.value = keyelsedocument.calc.display.value += key}function changeSign(){if (document.calc.display.value!="0")if(document.calc.display.value.substr(0,1) == "-")document.calc.display.value = document.calc.display.value.substr(1)elsedocument.calc.display.value = "-" + document.calc.display.value}//函数键function inputfunction(fun,shiftfun){endNumber=trueif (document.calc.shiftf.checked)document.calc.display.value=decto(funcalc(shiftfun,(todec(document.calc.display.value,carry))),c arry)elsedocument.calc.display.value=decto(funcalc(fun,(todec(document.calc.display.value,carry))),carry) document.calc.shiftf.checked=falsedocument.calc.hypf.checked=falseinputshift()}function inputtrig(trig,arctrig,hyp,archyp){if (document.calc.hypf.checked)inputfunction(hyp,archyp)elseinputfunction(trig,arctrig)}//运算符function operation(join,newlevel){endNumber=truevar temp=stack.substr(stIndexOf("(")+1)+document.calc.display.value while (newlevel!=0 && (newlevel<=(level.charAt(level.length-1)))){temp=parse(temp)level=level.slice(0,-1)}if (temp.match(/^(.*\d[\+\-\*\/\%\^\&\|x])?([+-]?[0-9a-f\.]+)$/)) document.calc.display.value=RegExp.$2stack=stack.substr(0,stIndexOf("(")+1)+temp+joindocument.calc.operator.value=" "+join+" "level=level+newlevel}//括号function addbracket(){endNumber=truedocument.calc.display.value=0stack=stack+"("document.calc.operator.value=" "level=level+0layer+=1document.calc.bracket.value="(="+layer}function disbracket(){endNumber=truevar temp=stack.substr(stIndexOf("(")+1)+document.calc.display.value while ((level.charAt(level.length-1))>0){temp=parse(temp)level=level.slice(0,-1)}document.calc.display.value=tempstack=stack.substr(0,stIndexOf("("))document.calc.operator.value=" "level=level.slice(0,-1)layer-=1if (layer>0)document.calc.bracket.value="(="+layerelsedocument.calc.bracket.value=""}//等号function result(){endNumber=truewhile (layer>0)disbracket()var temp=stack+document.calc.display.valuewhile ((level.charAt(level.length-1))>0){temp=parse(temp)level=level.slice(0,-1)}document.calc.display.value=tempdocument.calc.bracket.value=""document.calc.operator.value=""stack=""level="0"}//修改键function backspace(){if (!endNumber){if(document.calc.display.value.length>1)document.calc.display.value=document.calc.display.value.substring(0,document.calc.display.value .length - 1)elsedocument.calc.display.value=0}}function clearall(){document.calc.display.value=0endNumber=truestack=""level="0"layer=""document.calc.operator.value=""document.calc.bracket.value=""}//转换键function inputChangCarry(newcarry){endNumber=truedocument.calc.display.value=(decto(todec(document.calc.display.value,carry),newcarry)) carry=newcarrydocument.calc.sin.disabled=(carry!=10)document.calc.cos.disabled=(carry!=10)document.calc.tan.disabled=(carry!=10)document.calc.bt.disabled=(carry!=10)document.calc.pi.disabled=(carry!=10)document.calc.e.disabled=(carry!=10)document.calc.kp.disabled=(carry!=10)document.calc.k2.disabled=(carry<=2)document.calc.k3.disabled=(carry<=2)document.calc.k4.disabled=(carry<=2)document.calc.k5.disabled=(carry<=2)document.calc.k6.disabled=(carry<=2)document.calc.k7.disabled=(carry<=2)document.calc.k8.disabled=(carry<=8)document.calc.k9.disabled=(carry<=8)document.calc.ka.disabled=(carry<=10)document.calc.kb.disabled=(carry<=10)document.calc.kc.disabled=(carry<=10)document.calc.kd.disabled=(carry<=10)document.calc.ke.disabled=(carry<=10)document.calc.kf.disabled=(carry<=10)}function inputChangAngle(angletype){endNumber=trueangle=angletypeif (angle=="d")document.calc.display.value=radiansToDegress(document.calc.display.value)elsedocument.calc.display.value=degressToRadians(document.calc.display.value) endNumber=true}function inputshift(){if (document.calc.shiftf.checked){document.calc.bt.value="deg "document.calc.ln.value="exp "document.calc.log.value="expd"if (document.calc.hypf.checked){document.calc.sin.value="ahs " document.calc.cos.value="ahc " document.calc.tan.value="aht " }else{document.calc.sin.value="asin" document.calc.cos.value="acos" document.calc.tan.value="atan" }document.calc.sqr.value="x^.5" document.calc.cube.value="x^.3" document.calc.floor.value="小数" }else{document.calc.bt.value="d.ms" document.calc.ln.value=" ln " document.calc.log.value="log "if (document.calc.hypf.checked) {document.calc.sin.value="hsin" document.calc.cos.value="hcos" document.calc.tan.value="htan" }else{document.calc.sin.value="sin " document.calc.cos.value="cos " document.calc.tan.value="tan " }document.calc.sqr.value="x^2 " document.calc.cube.value="x^3 " document.calc.floor.value="取整" }}//存储器部分function clearmemory(){mem=0document.calc.memory.value=" " }function getmemory(){endNumber=truedocument.calc.display.value=decto(mem,carry)}function putmemory(){endNumber=trueif (document.calc.display.value!=0){mem=todec(document.calc.display.value,carry)document.calc.memory.value=" M "}elsedocument.calc.memory.value=" "}function addmemory(){endNumber=truemem=parseFloat(mem)+parseFloat(todec(document.calc.display.value,carry)) if (mem==0)document.calc.memory.value=" "elsedocument.calc.memory.value=" M "}function multimemory(){endNumber=truemem=parseFloat(mem)*parseFloat(todec(document.calc.display.value,carry)) if (mem==0)document.calc.memory.value=" "elsedocument.calc.memory.value=" M "}//十进制转换function todec(num,oldcarry){if (oldcarry==10 || num==0) return(num)var neg=(num.charAt(0)=="-")if (neg) num=num.substr(1)var newnum=0for (var index=1;index<=num.length;index++)newnum=newnum*oldcarry+hexnum.indexOf(num.charAt(index-1))if (neg)newnum=-newnumreturn(newnum)}function decto(num,newcarry){var neg=(num<0)if (newcarry==10 || num==0) return(num)num=""+Math.abs(num)var newnum=""while (num!=0){newnum=hexnum.charAt(num%newcarry)+newnumnum=Math.floor(num/newcarry)}if (neg)newnum="-"+newnumreturn(newnum)}//表达式解析function parse(string){if(string.match(/^(.*\d[\+\-\*\/\%\^\&\|x\<])?([+-]?[0-9a-f\.]+)([\+\-\*\/\%\^\&\|x\<])([+-]?[0-9a-f\.]+ )$/))return(RegExp.$1+cypher(RegExp.$2,RegExp.$3,RegExp.$4))elsereturn(string)}//数学运算和位运算function cypher(left,join,right){left=todec(left,carry)right=todec(right,carry)if (join=="+")return(decto(parseFloat(left)+parseFloat(right),carry))if (join=="-")return(decto(left-right,carry))if (join=="*")return(decto(left*right,carry))if (join=="/" && right!=0)return(decto(left/right,carry))if (join=="%")return(decto(left%right,carry))if (join=="&")return(decto(left&right,carry))if (join=="|")return(decto(left|right,carry))if (join=="^")return(decto(Math.pow(left,right),carry))if (join=="x")return(decto(left^right,carry))if (join=="<")return(decto(left<<right,carry))alert("除数不能为零")return(left)}//函数计算function funcalc(fun,num){with(Math){if (fun=="pi")return(PI)if (fun=="e")return(E)if (fun=="abs")return(abs(num))if (fun=="ceil")return(ceil(num))if (fun=="round")return(round(num))if (fun=="floor")return(floor(num))if (fun=="deci")return(num-floor(num))if (fun=="ln" && num>0)return(log(num))if (fun=="exp")return(exp(num))if (fun=="log" && num>0)return(log(num)*LOG10E)if (fun=="expdec")return(pow(10,num))//欢迎来到站长特效网,我们的网址是,很好记,zz站长,js就是js特效,本站收集大量高质量js代码,还有许多广告代码下载。