无法使简单的 If Else 语句起作用

Can't make a simple If Else statement work

您好,我正在制作一个简单的计数器,每次单击按钮时它都会计数到 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++;
})

试试这个代码。

您必须将 CSS 分配给两个 DIV,并将您的 if 语句代码放在 addEventListener 单击函数中。

const strongAttackBtn = document.querySelector('.strongAttackBtn');
const strongAttackBtnLoading =document.querySelector('.strongAttackBtnLoading');
var strongAttackCounter = 0;
strongAttackBtn.addEventListener('click', function(){
  strongAttackCounter++;
  
  if (strongAttackCounter === 3) {
    strongAttackCounter=0; // set it to zero again;
    
    strongAttackBtnLoading.style.width = '150px';
    strongAttackBtn.style.width = '150px';
    
  } else if (strongAttackCounter === 2) {
  
      strongAttackBtnLoading.style.width = '100px';
      strongAttackBtn.style.width = '100px';
      
  } else if (strongAttackCounter === 1) {
  
      strongAttackBtnLoading.style.width = '50px';
      strongAttackBtn.style.width = '50px';
      
  } else if (strongAttackCounter === 0) {
  
      strongAttackBtnLoading.style.width = '0px';
      strongAttackBtn.style.width = '0px';
      
  }
})
.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);
}
<div class="strongAttackBtnLoading"><input class="strongAttackBtn" type="button" value="strongAttackBtn"></div>