文章目录
- 1. 演示效果
- 2. 分析思路
- 3. 代码实现
1. 演示效果
2. 分析思路
给每个按钮添加点击事件,使用eval()
进行计算。
3. 代码实现
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title><style>.container {display: grid;grid-template-columns: 1fr 1fr 1fr 1fr;grid-template-rows: 1fr 1fr 1fr 1fr 1fr;width: 600px;height: 700px;padding: 30px;background: #495678;margin: 50px auto;border-radius: 30px;gap: 33px;}button {background: #72778b;border: none;color: white;font-size: 25px;text-align: center;border-radius: 50px;}button:hover {background: #575b6d;}.display:hover {background: #98d1dc;}.display {grid-column: 2/5;background: #98d1dc;}.clear,.equal {background: #e3844c;}.clear:hover,.equal:hover {background: #aa6339;}.operator {background: #fff;color: black;}.operator:hover {background: #ffffffb7;}</style></head><body><div class="container"><button class="clear">c</button><button class="display"></button><button class="number">7</button><button class="number">8</button><button class="number">9</button><button class="operator">+</button><button class="number">4</button><button class="number">5</button><button class="number">6</button><button class="operator">*</button><button class="number">1</button><button class="number">2</button><button class="number">3</button><button class="operator">-</button><button class="number">0</button><button class="operator">.</button><button class="operator">/</button><button class="equal">=</button></div><script>// 获取元素const buttons = document.querySelectorAll("button");const display = document.querySelector(".display");// 给显示在display的按钮添加点击事件 除了第一个和第二个for (let i = 2; i < buttons.length - 1; i++) {buttons[i].addEventListener("click", function () {display.innerHTML += this.innerHTML;});}// 清空按钮buttons[0].addEventListener("click", function () {display.innerHTML = "";});// 计算按钮buttons[buttons.length - 1].addEventListener("click", function () {display.innerHTML = eval(display.innerHTML);});</script></body>
</html>