javascript - 单击图像时如何播放声音,声音完成后会转到链接?
问题描述
我想在我的 html 中添加一个图像,单击该图像时,将调用一个播放声音的函数,然后在播放完声音后将您带到另一个网站/链接。我不确定这样做的方法,并查看了各种网站和文章。谢谢。
解决方案
- 首先,您需要向标签添加点击事件。
<img>
- 您需要一个音频标签才能播放声音。
- 您可以使用在步骤 1 中注册的事件触发play()
- 向音频标签添加结束事件以了解音频何时结束
- 使用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>
推荐阅读
- android - React Native Camera 显示带有加载微调器的空白屏幕
- ruby-on-rails - 简单的搜索表单在 Rails 中不起作用
- javascript - JsInterop:_framework/blazor.server.js 无法识别 .datetimepicker() 函数
- python - 方法的成员装饰器是否有更简单的语法?
- css - Wordpress 菜单不断加载内容。Z 索引不起作用
- sql - Sequelize Postgres - 选择不在 groupby 中的字段
- airflow - 更改 apache 气流网络服务器控制台上下文根路径
- javascript - 单击时重置 Ajax 计时器
- react-native - 来自子导航器屏幕的 openDrawer()
- python - MIDI 文件中的未知事件