[英]Javascript play sound on click, second button click stop first sound
我有這段代碼,按下按鈕時它會播放聲音,我想要的是從第一個單擊開始播放一個聲音,如果您單擊另一個按鈕,然后在其上方停止第一個按鈕並播放您單擊的下一個按鈕。
任何想法都很棒。
<!DOCTYPE html>
<head>
<title>Sounds</title>
</head>
<body>
<audio id="sound1" src="sounds/sound1.mp3"></audio>
<audio id="sound2" src="sounds/sound2.mp3"></audio>
<button onclick="document.getElementById('sound1').play()">Sound 1</button><br />
<button onclick="document.getElementById('sound2').play()">Sound 2</button><br />
</body>
</html>
提前致謝。
嘗試這樣的事情:
<audio id="sound1" src="sounds/sound1.mp3"></audio>
<audio id="sound2" src="sounds/sound2.mp3"></audio>
<button onclick="playSound1()">Sound 1</button><br />
<button onclick="playSound2()">Sound 2</button><br />
<script type="text/javascript">
var audio1 = document.getElementById('sound1');
var audio2 = document.getElementById('sound2');
function playSound1(){
if (audio1.paused !== true){
audio1.pause();
audio2.play();
}
else{
audio2.play();
}
}
function playSound2(){
if (audio2.paused !== true){
audio2.pause();
audio1.play();
}
else{
audio1.play();
}
}
</script>
盡管我建議您在按鈕標簽上使用addEventListener方法,而不是onclick屬性,因為它更易於維護。
謝謝
將相應音頻的ID放在按鈕上的data-target屬性中。 加載時,獲取按鈕並分配一個單擊處理程序,以重新加載當前音頻,將當前Audio元素設置為按鈕的目標,並播放當前Audio
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.