做了一个简单的计算器,在得到运算结果后可以再次进行运算,但是是练习,可能还存在一些小bug,欢迎指正下面是代码部分
1、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>Simple calculator</title><link rel="stylesheet" href="./css/index.css"></head><body><div class="calculator"><!-- 计算器的显示区域 --><div class="screen">0</div><!-- 按钮区域 --><ul class="keys"><li>AC</li><li>/</li><li>7</li><li>8</li><li>9</li><li>x</li><li>4</li><li>5</li><li>6</li><li>-</li><li>1</li><li>2</li><li>3</li><li>+</li><li>0</li><li>.</li><li>=</li></ul></div><script src="./js/index.js"></script></body></html>
2、CSS代码
* {padding: 0;margin: 0;box-sizing: border-box;}li {list-style: none;}.calculator {position: absolute;left: 0;top: 0;right: 0;bottom: 0;margin: auto;width: 260px;height: 400px;background-color: #dde1e7;border-radius: 10px;box-shadow: -3px -3px 7px #ffffff73,2px 2px 5px rgba(94,104,121,0.288);}.screen {width: 100%;height: 100px;padding: 10px;background-color: #dde1e7;border-radius: 10px;box-shadow: -3px -3px 7px #ffffff73,2px 2px 5px rgba(94,104,121,0.288);line-height: 100px;color: #595959;font-size: 30px;text-align: right;white-space: nowrap;overflow: hidden;}.keys {height: 300px;}.keys li {float: left;width: 65px;height: 60px;line-height: 60px;text-align: center;font-size: 23px;border-radius: 5px;box-shadow: -3px -3px 7px #ffffff73,2px 2px 5px rgba(94,104,121,0.288)/* border: 1px solid #999; *//* box-shadow: 0px 1px 2px 0px; */}.keys li:active{color: #3498db;box-shadow: inset -3px -3px 7px #ffffff73,inset 2px 2px 5px rgba(94,104,121,0.288)}.keys li:nth-child(1) {width: 195px;}.keys li:nth-last-child(1){width: 130px;}
3、JavaScript代码
window.onload = function () {const screen = document.querySelector('.screen')const keys = document.querySelector('.keys')const lis = keys.querySelectorAll('li')// 运算符号let BDFH = ''// 保存数字let num1 = ''let num2 = ''// 运算结果let result = ''for (let i = 0; i < lis.length; i++) {lis[i].addEventListener('click', function () {let text = lis[i].innerText// 清除键if (text == 'AC') {BDFH = ''num1 = ''num2 = ''result = ''screen.innerHTML = '0'}// 运算符号else if (text == '/' || text == '+' || text == '-' || text == 'x') {BDFH = text}// 算结果else if (text == '=') {if (num1 != '' && num2 != '') {num1 = parseFloat(num1)num2 = parseFloat(num2)if (BDFH == '+') {result = num1 + num2}if (BDFH == '-') {result = num1 - num2}if (BDFH == 'x') {result = num1 * num2}if (BDFH == '/') {result = num1 / num2}screen.innerText = result// 如果有结果,将结果作为第一个数来进行计算,实现连续的运算num1 = resultnum2 = ''BDFH = ''}}// 数字键else {if (BDFH != '') {if (text == '.' && num2.indexOf('.') > 0) {num2 = num2} else {num2 += text}screen.innerText = num2}else {if (text == '.' && num1.indexOf('.') > 0) {num1 = num1}else {num1 += text}screen.innerText = num1}}})}}
如果觉得《JavaScript实现可以连续运算的简易计算器》对你有帮助,请点赞、收藏,并留下你的观点哦!