如何在一个页面上多次使用音频播放器?

时间:2018-05-11 22:16:35

标签: javascript jquery html css audio

我有一个播客播放器:

<div class="pcast-player">
  <div class="pcast-player-controls">
  <button class="pcast-play"><i class="fas fa-play fa-fw"></i></button>
  <button class="pcast-pause"><i class="fas fa-pause fa-fw"></i></button>
  <progress class="pcast-progress" value="0"></progress>
  <button class="pcast-mute" id="mute"><i class="fas fa-volume-up fa-fw"></i></button>
  <button class="pcast-unmute" id="unmute"><i class="fas fa-volume-off fa-fw"></i></button>
  <ul>
    <li class="pcast-currenttime pcast-time">00:00:00</li>
    <li class="pcast-duration pcast-time">00:00</li>
  </ul>
  </div>
  <audio src="/audio/intro.mp3" id="mute-toggle"></audio>
</div>

现在,是否可以在单个页面上多次使用此播放器而不必每次更改类别(pcast-play1,pcast-play2等...)?所以,如果我点击第一个没有触发所有这些......

我在想数据 - *,但我不确定如何处理这些...请帮助,thx

JS(开始)

var pcastPlayers = document.querySelectorAll('.pcast-player');

for(i=0;i<pcastPlayers.length;i++) {
var player = pcastPlayers[i];
var audio = player.querySelector('audio');
var play = player.querySelector('.pcast-play');
var pause = player.querySelector('.pcast-pause');
var progress = player.querySelector('.pcast-progress');
var mute = player.querySelector('.pcast-mute');
var unmute = player.querySelector('.pcast-unmute');
var currentTime = player.querySelector('.pcast-currenttime');
var duration = player.querySelector('.pcast-duration');

var currentSpeedIdx = 0;

play.addEventListener('click', function(){
  this.style.display = 'none';
  pause.style.display = 'inline-block';
  pause.focus();
  audio.play();
}, false);

pause.addEventListener('click', function(){
  this.style.display = 'none';
  play.style.display = 'inline-block';
  play.focus();
  audio.pause();
}, false);

依旧......

1 个答案:

答案 0 :(得分:1)

在每个循环中,您将覆盖并发变量和eventListeners,因为它们是全局的而不在for循环的范围内。避免这种情况的一种简单方法是简单地使用letconst而不是var,因为它们是a)块范围b)在现代JS开发中通常首选。

请参阅working example,其中两个音频文件是分开控制的

https://jsfiddle.net/4x0esndj/