文章目录
- 效果
- 代码
- html
- css
- js
其他demo:https://blog.csdn.net/karshey/article/details/132585901
效果
效果预览:https://codepen.io/karshey/pen/RwERjGz
参考:
js实现仿华为手机计算器,兼容电脑和手机屏幕_dengluandai1740的博客-CSDN博客
Javascript iOS Style Calculator
Javascript Calculator
代码
本想尝试不用eval()而是手动实现的,后来发现细节太多了,越写问题越多。。所以就算了
思路:
- 把点击的数字或符号拼接为字符串,每次点击=时直接放到eval中计算
- 注意将
x
改为*
等 - html用table实现,占两行的=用
rowspan
实现
注意,table的margin是失效的。
html
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Calculator</title><link rel="stylesheet" href="style.css"><body><div class="calculator"><div class="screen"><div class="in" id="in"></div><div class="out" id="out"></div></div><div class="btn"><table><tr class="op"><td onclick="clearSceen()">C</td><td onclick="command('/')">/</td><td onclick="command('x')">x</td><!-- 打< 要写< --><td onclick="del()"><-</td></tr><tr><td onclick="command(7)">7</td><td onclick="command(8)">8</td><td onclick="command(9)">9</td><td class="op" onclick="command('-')">-</td></tr><tr><td onclick="command(4)">4</td><td onclick="command(5)">5</td><td onclick="command(6)">6</td><td class="op" onclick="command('+')">+</td></tr><tr><td onclick="command(1)">1</td><td onclick="command(2)">2</td><td onclick="command(3)">3</td><td class="equal" rowspan="2" onclick="cal()">=</td></tr><tr><td onclick="command('%')">%</td><td onclick="command(0)">0</td><td onclick="command('.')">.</td></tr></table></div></div>
</body></html><script src="index.js"></script>
css
* {margin: 0;padding: 0;
}html,
body {overflow: hidden;
}.calculator {width: 300px;height: 445px;margin: 100px auto;border: 1px solid #E4E4E4;position: relative;
}.in,
.out {height: 60px;line-height: 60px;text-align: right;padding: 0 10px;overflow: hidden;
}.in {font-weight: 700;font-size: 20px;
}.out {color: #a9a9a9;font-size: 16px;
}.btn {position: absolute;bottom: 0px;
}.btn td {width: 75px;height: 60px;line-height: 60px;/* 左右居中 */text-align: center;font-size: 20px;border: 1px solid #E4E4E4;/* hover时是手掌形状 */cursor: pointer;
}/* 所有按钮在hover时都有阴影 除了= */
.btn td:hover:not(.equal) {background-color: #ebebeb;
}.op {background-color: #F5F5F5;color: #00ACC2;
}.equal {background-color: #00ACC2;color: #fff;
}
js
let calIn = document.getElementById('in')
let calOut = document.getElementById('out')function command(str) {calIn.innerHTML = '' ? str : calIn.innerHTML + str
}function cal() {calOut.innerHTML = eval(calIn.innerHTML.replace(/x/g, '*').replace(/%/, '/100'));if (calIn.innerHTML == 'undefined' || calOut.innerHTML == 'undefined') calOut.innerHTML = ''// else {// calIn.innerHTML = calOut.innerHTML// calOut.innerHTML = ''// }
}function clearSceen() {calIn.innerHTML = ''calOut.innerHTML = ''
}function del() {if (calIn.innerHTML.length) {calIn.innerHTML = calIn.innerHTML.slice(0, calIn.innerHTML.length - 1)}
}