【发布时间】:2021-12-08 20:52:20
【问题描述】:
您好,我正在制作一个简单的计数器,每次单击按钮时计数到 3。计数器工作得很好,因为我可以看到他在控制台中的变化。问题是,我的 JS 并没有影响 CSS。当我删除 else 语句并只留下一个时,这就是正在工作的那个。
CSS。注意:strongAttackBtn 和 strongAttackBtnLoading 在同一个 div 中。
.strongAttackBtn {
height: 50px;
width: 150px;
color: black;
font-weight: 800;
}
.strongAttackBtnLoading {
position: absolute;
height: 50px;
width: 150px;
background-color: rgba(0,0,0,0.5);
}
JS
const strongAttackBtnLoading = document.querySelector('.strongAttackBtnLoading');
const strongAttackBtn = document.querySelector('.strongAttackBtn');
let strongAttackCounter = 0;
if (strongAttackCounter === 3) {
strongAttackBtnLoading.style.width = '150px';
} else if (strongAttackCounter === 2) {
strongAttackBtnLoading.style.width = '100px';
} else if (strongAttackCounter === 1) {
strongAttackBtnLoading.style.width = '50px';
} else if (strongAttackCounter === 0) {
strongAttackBtnLoading.style.width = '0px';
}
strongAttackBtn.addEventListener('click', function(){
strongAttackCounter++;
})
【问题讨论】:
-
你的 if 语句块应该在事件监听器中。
-
就这么简单,我不知道我在想什么。谢谢
-
你也可以让你的 if/else 一行
strongAttackBtnLoading.style.width = (strongAttackCounter < 150 ? strongAttackCounter * 50 : 150) + 'px'; -
劳伦斯非常好用。 “:”符号有什么作用?我不明白为什么这段代码有效。
标签: javascript if-statement queryselector