【问题标题】:jQuery Soundboard - Playing ONE Button turns off all the other buttonsjQuery Soundboard - 播放一个按钮会关闭所有其他按钮
【发布时间】:2015-12-16 15:33:26
【问题描述】:

我正在创建一个 jQuery/PHP 音板,如果我单击一个按钮,我试图弄清楚如何编码,这会停止附加到所有其他按钮的 HTML5 音频。到目前为止,这是我的代码:

查询:

$(function() {
            $("audio").removeAttr("controls").each(function(i, audioElement) {
                var audio = $(this);
                var that = this; //closure to keep reference to current audio tag
                $("#doc").append(
                    $('<button>'+audio.attr("title")+'</button>').toggle(
                        function() {
                            that.play();
                            $(this).addClass('playing');
                        }, 
                        function(){
                            that.pause(); that.currentTime = 0;
                            $(this).removeClass('playing');
                        }));
            });
        });
    </script>

PHP:

<?php foreach($files as $file) { ?>
     <?php $title = str_replace(".mp3", "", str_replace("clips/", "", $file)); ?>
     <audio src="<?php echo $file; ?>" controls autobuffer="true" title="<?php echo $title ?>"></audio>
<?php } ?>

【问题讨论】:

    标签: javascript php jquery audio dynamic


    【解决方案1】:

    修改后的 jQuery:

    $('<button>'+audio.attr("title")+'</button>').click(
       function(e) {
          var playing = $(this).hasClass("playing");
          $("audio").each(function(i, audioElement){
             this.pause();
             this.currentTime = 0;
          });
    
          $("button").each(function( i ) {
             $(this).removeClass('playing');
          });
    
          if (!playing){
             that.play();
             $(this).addClass('playing');
          }
       })
    );
    $("audio").bind("ended", function(){ $("button").removeClass('playing'); });
    

    说明:

    当您单击任何按钮时,如果该按钮具有 PLAYING 类,它会声明一个变量。然后,它会自动停止所有音频并将它们倒回 0。然后它会从每个按钮中删除 PLAYING 类。最后,它会检查您刚刚单击的按钮是否具有 PLAYING 类;如果没有,则将类 PLAYING 添加到按钮,并播放附加到该按钮的音频。

    音频播放完毕后,底部添加的行会触发,PLAYING 类会自动删除

    【讨论】:

      猜你喜欢
      • 2022-12-18
      • 2021-08-23
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 2017-11-15
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      相关资源
      最近更新 更多