document.addEventListener("DOMContentLoaded", function() {
const btns = document.querySelectorAll('.num');
const screen = document.querySelector('.screen');
const equal = document.querySelector('.btn-equal');
const clear = document.querySelector('btn-clear');
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function () {
let number = btns[i].getAttribute('data-num');
screen.value += number;
})
}
});
*{
padding: 0;
margin: 0;
box-sizing: border-box; /*learn box-sizing*/
}
body {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.calculator {
flex: 0 0 60%;
}
.screen {
width: 100%;
background: black;
color: white;
font-size: 6rem;
padding: 0.5rem;
border: none;
padding: 0.5rem;
}
.buttons {
display: flex;
flex-wrap: wrap;
transition: all 0.5s linear;
}
button {
flex: 0 0 25%;
border: 1px solid black;
padding: 0.25rem 0;
transition: all 2s ease; /*learn tansition*/
}
button:hover {
background: blue;
color: white;
}
.btn-yellow {
background: orange;
color: white;
}
.btn-grey {
background: lightgrey;
color: white;
}
.btn-equal {
background: limegreen;
}
.btn-clear {
background: red;
}
.btn {
font-size: 3.5rem;
}
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<section class="calculator">
<form>
<input type="text" name="" id="" class="screen">
</form>
<div class="buttons">
<!-- yellow buttons -->
<button type="button" class="num btn btn-yellow" data-num="+">+</button>
<button type="button" class="num btn btn-yellow" data-num="*">*</button>
<button type="button" class="num btn btn-yellow" data-num="/">/</button>
<button type="button" class="num btn btn-yellow" data-num="-">-</button>
<!-- grey buttons -->
<button type="button" class="num btn btn-grey" data-num=".">.</button>
<button type="button" class="num btn btn-grey" data-num="9">9</button>
<button type="button" class="num btn btn-grey" data-num="8">8</button>
<button type="button" class="num btn btn-grey" data-num="7">7</button>
<button type="button" class="num btn btn-grey" data-num="6">6</button>
<button type="button" class="num btn btn-grey" data-num="5">5</button>
<button type="button" class="num btn btn-grey" data-num="4">4</button>
<button type="button" class="num btn btn-grey" data-num="3">3</button>
<button type="button" class="num btn btn-grey" data-num="2">2</button>
<button type="button" class="num btn btn-grey" data-num="1">1</button>
<button type="button" class="num btn btn-grey" data-num="0">0</button>
<button type="button" class="num btn btn-grey btn-equal">=</button>
<button type="button" class="num btn btn-grey btn-clear">C</button>
</div>
</section>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
伙计们,所以我正在尝试制作一个简单的计算器,现在我正在编写该函数来处理单击的所有按钮,除了等号和清除按钮。我现在要做的就是在计算器的输入屏幕上显示按钮的值。我虽然收到此错误:未捕获的TypeError:无法读取未定义的属性'getAttribute' 在HTMLButtonElement。 我环顾四周,大多数人都这样说,因为我的脚本在DOM之前加载,但是我在其中放置了“ DOMContentLoaded”事件,但仍然无法使其正常工作。任何帮助都会很棒。