【问题标题】:Bootstrap modal with youtube video not pausing when closed带有 youtube 视频的引导模式在关闭时不会暂停
【发布时间】:2017-06-08 17:22:12
【问题描述】:

我有多个带有 youtube 视频的引导模式,我想在模式关闭时暂停而不是停止。我已经搜索过,但找不到一个很好的解决方案。一旦我关闭模式并再次打开,视频就会从头开始。我的代码是

$(document).ready(function() {
  $('.modal').each(function() {
    var src = $(this).find('iframe').attr('src');

    $(this).on('click', function() {

      $(this).find('iframe').attr('src', '');
      $(this).find('iframe').attr('src', src);

    });
  });
});


function checkForYoutubeVideos(){
            if ( jQuery('.youtubeplayer').length ){
                players = {};
                var tag = document.createElement('script');
                tag.src = "https://www.youtube.com/iframe_api";
                var firstScriptTag = document.getElementsByTagName('script')[0];
                firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
            }
        }
        function onYouTubeIframeAPIReady(e){
            jQuery('iframe.youtubeplayer').each(function(i){
                var youtubeiframeClass = jQuery(this).attr('id');
                players[youtubeiframeClass] = new YT.Player(youtubeiframeClass, {
                    events: {
                        onReady: onPlayerReady,
                        onStateChange: onPlayerStateChange,
                        onError: onPlayerError
                    }
                });
            });
            pauseFlag = false;
        }
        function onPlayerError(e){
            var videoTitle = e['target']['B']['videoData']['title'];
            ga('send', 'event', 'Error', 'Youtube API', videoTitle + ' (Code: ' + e.data + ')', {'nonInteraction': 1}); //Log the API error
        }
        function onPlayerReady(e){
           //Do something when player is ready.
        }
        function onPlayerStateChange(e){
            var videoTitle = e['target']['B']['videoData']['title'];
            if ( e.data == YT.PlayerState.PLAYING ){
                ga('send', 'event', 'Youtube', 'Play', videoTitle);
                pauseFlag = true;
            }
            if ( e.data == YT.PlayerState.ENDED ){
                ga('send', 'event', 'Youtube', 'Finished', videoTitle, {'nonInteraction': 1});
            } else if ( e.data == YT.PlayerState.PAUSED && pauseFlag ){
                ga('send', 'event', 'Youtube', 'Pause', videoTitle);
                pauseFlag = false;
            }
        }
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class="bs-example">
  <a href="#videoModal2" target="_blank" class="ga_track wp-read" data-toggle="modal">WATCH VIDEO &nbsp; <span class="next-arrow"></span> <span class="next-arrow"></span></a>

  <!-- Modal HTML -->
  <div id="videoModal2" class="modal fade">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        </div>
        <div class="modal-body">
          <iframe class="youtubeplayer" width="100%" height="315" src="https://www.youtube.com/embed/..." frameborder="0" allowfullscreen></iframe>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

【问题讨论】:

    标签: javascript jquery twitter-bootstrap youtube bootstrap-modal


    【解决方案1】:

    基于this answer。 您必须使用 youtube iframe api。要首先使用它,您必须通过在链接中 iframe 查询字符串的末尾添加 &enablejsapi=1 来启用它。示例:

    <iframe width="560" height="315" class="youtubeplayer" id="youtubeplayer" src="https://www.youtube.com/embed/34Na4j8AVgA?list=PLDcnymzs18LWrKzHmzrGH1JzLBqrHi3xQ&enablejsapi=1" frameborder="0" allowfullscreen></iframe>
    

    接下来您需要使用引导模式事件“shown.bs.modal”和“hidden.bs.modal”来检查模式何时打开以及何时关闭。

    然后我创建了一个函数“toggleVideo”,它向 iframe 发送消息,这是手动嵌入 iframe 时与 youtube API 通信的方式。 “postMessage”是一个 HTML5 功能,大多数现代浏览器都支持 postMessage,尽管 Internet Explorer 7 不支持它。

    $(document).ready(function() {
        $('.modal').each(function() {
            $this = $(this);
            $this.on('shown.bs.modal', function() {
                toggleVideo('playVideo', $(this));
            });
    
            $this.on('hidden.bs.modal', function(){
               toggleVideo('pauseVideo', $(this));
            })
       });
    
        function toggleVideo(state, div) {
            var iframe = div.find("iframe")[0].contentWindow;
            iframe.postMessage('{"event":"command","func":"' + state + '","args":""}', '*');
        }
    });  
    

    【讨论】:

    • 感谢您,但是当我在同一页面中添加另一个模式时,它会停止工作,有时当您单击打开模式时它会播放相同的视频。
    • 我更新了脚本以支持视频的多模态
    • 嗨,如果我想添加 GA 跟踪事件我正在使用上面编辑过的代码,但它没有跟踪任何事件有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 2014-07-26
    • 2018-05-12
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多