2017-08-20 55 views
0

我有點擊停止音頻播放器的問題。玩家成功啓動,但當我再次點擊時,無法停止。你能幫我解決嗎?下面是一個代碼:無法停止音頻點擊

$(".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(); 
    } 


}); 
+0

創建每點擊一個新的音頻播放器,我認爲你有一個問題,使用'toggleClass()' –

回答

1

,如果你想裝載取決於按鈕點擊一個新的音頻源,但使音頻元素全局和檢查,如果它被定義然後切換音頻繼續這個例子可以得到更復雜播放/暫停。

// 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>

+0

謝謝:)運行完美! – Ganga

+0

你最受歡迎:) –