首页 > 解决方案 > 单击图像时如何播放声音,声音完成后会转到链接?

问题描述

我想在我的 html 中添加一个图像,单击该图像时,将调用一个播放声音的函数,然后在播放完声音后将您带到另一个网站/链接。我不确定这样做的方法,并查看了各种网站和文章。谢谢。

标签: javascripthtml

解决方案


  1. 首先,您需要向标签添加点击事件<img>
  2. 您需要一个音频标签才能播放声音。
  3. 您可以使用在步骤 1 中注册的事件触发play()
  4. 向音频标签添加结束事件以了解音频何时结束
  5. 使用location.href导航到另一个 URL

如果您想使用样式,可以隐藏音频播放器。

const audio = document.querySelector('#audio');
audio.load(); //call this to preload the audio without playing

const picture = document.querySelector('#picture');

//add onclick event to image
picture.addEventListener('click', (e) => {
  //call this to play the audio right away
  audio.play();
});

// register an event to know when the audio ended
audio.addEventListener('ended', (e) => {

  // go to another url
  location.href = 'https://w3.org';

});
audio {
  /* uncomment to hide the player */
  /* display: none; */
}
<p>Click the image to play sound</p>
<img id="picture" src="http://media.w3.org/2010/05/bunny/poster.png" width="200">

<br>

<audio id="audio" controls="controls">
  <source id="audioSource" src="http://media.w3.org/2010/05/sound/sound_5.mp3"></source>
  Your browser does not support the audio format.
</audio>


推荐阅读