使用 document.querySelectorAll(‘audio’) 方法获取页面上所有的 audio 标签元素。
然后,通过 forEach 循环为每个 audio 标签添加 play 事件监听器。
当某个 audio 标签触发 play 事件时,再次遍历所有的 audio 标签,将除了正在播放的 audio 标签之外的其他 audio 标签都暂停播放。
请确保将 src 属性的值替换为实际的音频文件路径。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>禁止两个 audio 标签同时播放</title>
</head>
<body>
<audio id="audio1" controls>
<source src="audio1.mp3" type="audio/mpeg">
</audio>
<audio id="audio2" controls>
<source src="audio2.mp3" type="audio/mpeg">
</audio>
<script>
const audioElements = document.querySelectorAll('audio');
audioElements.forEach((audio) => {
audio.addEventListener('play', function () {
audioElements.forEach((otherAudio) => {
if (otherAudio!== this) {
otherAudio.pause();
}
});
});
});
</script>
</body>
</html>