【问题标题】:Changing sound effect on a function when variable changes变量更改时更改函数的声音效果
【发布时间】:2019-09-18 16:00:47
【问题描述】:

我正在为一个 JS 班写作业,老师希望我们在开火时有武器声音,但在弹药用完时停止发出声音。 当枪开火时,我有声音效果,但是当用 0 弹药点击时它会继续发出声音。

我尝试执行 else{} 函数,但这会破坏浏览器中的“弹药显示”,并且声音会继续播放。

HTML:

<input type="button" value="Heal" class="shoot" onclick="shoot();">
<audio id="heal" src="sound/heal.mp3">

JS:从最多 6 发开始显示弹药,有 6 发备用,每次发射都会倒计时。

function shoot() {
  if (currentAmmo > 0) {
    currentAmmo--;
  }
  var shoot = document.getElementById("shoot");
  shoot.play();
  updatescreen();

  function updatescreen() {
    document.getElementById("total-ammo").innerHTML = "Bullets in Gun:</br>" + totalAmmo;
    document.getElementById("current-ammo").innerHTML = "Reload Ammo:</br>" + currentAmmo;
  }

【问题讨论】:

    标签: javascript html audio soundeffect


    【解决方案1】:

    您只需将播放命令移动到 if 条件中。

      if (currentAmmo > 0) {
        currentAmmo--;
      var shoot = document.getElementById("shoot");
      shoot.play();
      }
    
      updatescreen();
    

    【讨论】:

      【解决方案2】:

      play 调用放在您的if 语句中,这样只有在语句为真时才会播放:

      function shoot() {
        if (currentAmmo > 0) {
          currentAmmo--;
          document.getElementById("shoot").play();
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多