我正在尝试编写一些JS,如果音频播放了一秒钟或更长时间,它将把正方形从蓝色变成黄色。目前,似乎没有任何变化。这是我自己尝试编写的JS的第一部分,因此,如果有人提出了建议,那将是很棒的。



// sound from https://www.w3schools.com/tags/horse.ogg

// when one second or more of the audio is played, change the square from blue to yellow

window.onload = function() {

  function changeColor() {
    var timedChange = document.getElementById("audioPlayer").currentTime;
    if (timedChange >= 1) {
      document.getElementById("yellow").style.display = "block";
    } else {
      document.getElementById("yellow").style.display = "none";
    }
  };
}

#blue {
  width: 200px;
  height: 200px;
  background-color: blue;
}

#yellow {
  width: 200px;
  height: 200px;
  background-color: yellow;
  position: absolute;
  top: 8px;
  display: none;
}

#audioPlayer {
  position: absolute;
  right: 500px;
  top: 10px;
}

<div id="blue"></div>

<div id="yellow"></div>

<audio id="audioPlayer" src="https://www.w3schools.com/tags/horse.ogg" type="audio" onclick="changeColor()" controls>
</audio>

最佳答案

const audio = document.getElementById("audioPlayer");

// show yellow square after 1sec (1000 millisec) of audio playback
audio.onplay = () => {
  setTimeout( () => {
    document.getElementById("yellow").style.display = "block";
  }, 1000);
};

// hide the yellow square immedeately when the audio stops
audio.onpause = () => {
  document.getElementById("yellow").style.display = "none";
};

#blue {
  width: 200px;
  height: 200px;
  background-color: blue;
}

#yellow {
  width: 200px;
  height: 200px;
  background-color: yellow;
  position: absolute;
  top: 8px;
  display: none;
}

#audioPlayer {
  position: absolute;
  right: 500px;
  top: 10px;
}

<div id="blue"></div>

<div id="yellow"></div>

<audio id="audioPlayer" src="https://www.w3schools.com/tags/horse.ogg" type="audio" controls>
</audio>

关于javascript - JavaScript代码段可根据音频播放进行视觉更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58469589/

10-13 06:00