[英]Cant stop audio on click
我在點擊停止音頻播放器時遇到問題。 播放器成功啟動,但是當我再次單擊時無法停止。 你能幫我嗎? 這是一個代碼:
$(".portfolio-listen").click(function(e) {
e.preventDefault();
var audioUrl = $(this).attr("href");
var audioElement = document.createElement("audio");
audioElement.setAttribute('src', audioUrl);
$(this).toggleClass("playing");
if ($(this).hasClass("playing")) {
audioElement.play();
} else {
audioElement.pause();
}
});
如果您希望根據單擊的按鈕加載新的音頻源,但是將音頻元素設置為全局並檢查是否已定義,然后切換音頻播放/暫停,此示例可能會變得更加復雜。
// for demo purpose, use var audioUrl = $(this).href('href') var audioUrl = 'https://allthingsaudio.wikispaces.com/file/view/Shuffle%20for%20K.M.mp3/139190697/Shuffle%20for%20K.M.mp3'; // Make audioElement global var audioElement; $(".portfolio-listen").click(function(e) { e.preventDefault(); if(!audioElement){ audioElement = document.createElement("audio"); audioElement.setAttribute('src', audioUrl); } $(this).toggleClass("playing"); if ($(this).hasClass("playing")) { audioElement.play(); } else { audioElement.pause(); } });
button { background: #e91e63; } button.playing { background: #8bc34a; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script> <button class="portfolio-listen">Play</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.