我在点击停止音频播放器时遇到问题。播放器成功启动,但是当我再次单击时无法停止。你能帮我吗?这是一个代码:

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

07-28 01:29
查看更多