twitter-bootstrap Bootstrap Modals 和 Youtube:自动播放和关闭时停止

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16755364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 17:12:46  来源:igfitidea点击:

Bootstrap Modals & Youtube: Autoplay and Stop on Close

jquerytwitter-bootstrapyoutubemodal-dialog

提问by Benjamin Morrison

I need to be able to autoplay a youtube video when a Twitter Bootstrap modal is opened and subsequently stop that video on close.

我需要能够在 Twitter Bootstrap 模式打开时自动播放 youtube 视频,然后在关闭时停止该视频。

I know this question has been asked before, but the answers I can find would lead to a LOT of javascript code for a page that contains MANY videos and I am trying to cut down on the bloat. So far I have the following working for individual videos, but the issue is that each modal and each video must have this javascript code repeated with the proper variables.

我知道以前有人问过这个问题,但我能找到的答案会导致包含许多视频的页面有很多 javascript 代码,我正试图减少膨胀。到目前为止,我对单个视频有以下工作,但问题是每个模态和每个视频都必须使用适当的变量重复此 javascript 代码。

$('#vidThumbnail-1').click(function () {
        var src = 'http://www.youtube.com/embed/8bKmrhI-YT8?&autoplay=1';
        $('#vid1').modal('show');
        $('#vid1 iframe').attr('src', src);

      //Fit Vids Implamented Below for Mobile Compatibility
        $("#vid1Thumbnail-1 iframe").wrap("<div class='flex-video'/>");
        $(".flex-video").fitVids();
    });
$('#vid1 button').click(function () {
        $('#vid1 iframe').removeAttr('src');
    });

HTML:

HTML:

<div id="vidThumbnail-1"><img src="http://img.youtube.com/vi/8bKmrhI-YT8/0.jpg" /></div>

<div id="vid1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-body">
        <iframe src="http://www.youtube.com/embed/8bKmrhI-YT8" width="640" height="360" frameborder="0" allowfullscreen></iframe>   
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    </div>
  </div>

This gets bloated when you have 20 videos and 20 modals! Is there a way to utilize the Data Attributes method of initiating a modal built-into bootstrap rather than call it individually, while still modifying the iframe src within only the target modal? The link to open the modal would then be:

当您有 20 个视频和 20 个模态时,这会变得臃肿!有没有办法利用数据属性方法来启动内置于引导程序的模态而不是单独调用它,同时仍然只在目标模态内修改 iframe src?打开模态的链接将是:

<a href="#vid1" role="button" data-toggle="modal">
<img src="http://img.youtube.com/vi/8bKmrhI-YT8/0.jpg"></a>

Then:

然后:

  1. Read the existing src attribute of the iframe in the target modal (set that to a variable?)
  2. Append the existing src attribute with "&autoplay=1" to initiate the video.
  3. Replace the src attribute with the original upon closing the modal (via the button specifically like it is above is fine).
  1. 读取目标模式中 iframe 的现有 src 属性(将其设置为变量?)
  2. 使用“&autoplay=1”附加现有的 src 属性以启动视频。
  3. 在关闭模态时将 src 属性替换为原始属性(通过上面的按钮就可以了)。

This way I would not need to write script for each individual modal, saving a lot of time AND bloated JS. However, I have no idea where to start modifying the bootstrap.js to accomplish this and I'm not experienced in JS (or any) programming. Thanks for any help you can give me!

这样我就不需要为每个单独的模态编写脚本,节省了大量时间和臃肿的 JS。但是,我不知道从哪里开始修改 bootstrap.js 来实现这一点,而且我没有 JS(或任何)编程经验。感谢你给与我的帮助!

回答by Francesco Borzi

My solution:

我的解决方案:

  • do notadd &amp;autoplay=1to the iframe src manually
  • 不要&amp;autoplay=1人工的IFRAME SRC

then add this script:

然后添加这个脚本:

var videoSrc = $("#myModal iframe").attr("src");

$('#myModal').on('show.bs.modal', function () { // on opening the modal
  // set the video to autostart
  $("#myModal iframe").attr("src", videoSrc+"&amp;autoplay=1");
});

$("#myModal").on('hidden.bs.modal', function (e) { // on closing the modal
  // stop the video
  $("#myModal iframe").attr("src", null);
});

回答by Ali ?zy?ld?r?m

                    <div class="close-button">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span></button>
                    </div>

   $('.close').on('click', function (e) {
        $("#myModal iframe").attr("src", null);
    });

回答by Brit Finnegan

I couldn't find a dynamic way to handle this issue, so I created a dynamic way to handle this for a site that we are working on.

我找不到处理此问题的动态方法,因此我为我们正在处理的站点创建了一种动态方法来处理此问题。

Here are the links:

以下是链接:

<li><a href="#" data-toggle="modal" data-target="#video1">Video: video 1</a></li>
<li><a href="#" data-toggle="modal" data-target="#video2">Video: video 2</a></li>

Here are the modals:

以下是模态:

<div id="video1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/vidpath" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>
<div id="video2" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/vidpath2" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>

Here is the script:

这是脚本:

// autoplay video functionality
$( "[data-target^='#video']" ).click(function() { 
    // get the ID of the clicked video
    var dataTarget = $(this).attr("data-target");
    dataTarget = dataTarget.substring(1,7); 
    var vidId = '#'+dataTarget; 

    // get the vid src
    var vidSrc = $(vidId+ " iframe").attr('src');

    // create the autoplay
    var vidSrcAuto = vidSrc+'?autoplay=1'; 

    // get the iframe element
    var iframeEl = $(vidId+ " iframe"); 


    $(vidId).on('show.bs.modal', function () {  
        $(iframeEl).attr("src", vidSrcAuto);
    });

    $(vidId).on('hidden.bs.modal', function (e) {  
        $(iframeEl).attr("src", vidSrc);  
    });   

}); 

回答by Khadka Pushpendra

Hello @Benjamin Morrison Hope you got the solution already, I am answering this for other user who are still searching for same solution

你好@Benjamin Morrison 希望你已经得到了解决方案,我正在为仍在寻找相同解决方案的其他用户回答这个问题

$(document).ready(function() {
  $('.modalclick').on('click', function(e) {
    e.preventDefault();
    var src = $(this).attr('href');
    $('#myModal').modal('show');
    $('#myModal iframe').attr('src', src);
  });
  //auto close or pause on model hide
  $("#myModal").on('hidden.bs.modal', function(e) {
    $("#myModal iframe").attr("src", '');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="modal fade" id="myModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
      </div>
      <div class="modal-body">
        <iframe src="" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

      </div>
      <div class="modal-footer">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">SKIP >></button>

      </div>
    </div>
  </div>
</div>
<a class="modalclick" href="https://www.youtube-nocookie.com/embed/3j4nia24Oms?rel=0&showinfo=0&autoplay=1">click me</a><br>
<a class="modalclick" href="https://www.youtube.com/embed/ycK617mKlvA?rel=0&showinfo=0&autoplay=1">click me 1</a><br>
<a class="modalclick" href="https://www.youtube.com/embed/z329gFDUJis?rel=0&showinfo=0&autoplay=1">click me 2</a>

Just Add Youtube Embed url on href tag of clickable link, you can make as many as link you link. @Benjamin in your case keep image inside anchor tag so that Image is clickable.

只需在可点击链接的 href 标签上添加 Youtube Embed url,您就可以制作与您链接的链接一样多的链接。@Benjamin 在您的情况下将图像保留在锚标签内,以便图像可点击。

回答by Daniel.P.

The clean way is to enable JS Youtube APIfor embedded iframe. Just by adding enablejsapiparameter. As of year 2020 this was only working solution for stop video without hacks.

干净的方法是为嵌入式 iframe启用JS Youtube API。只需添加enablejsapi参数。截至 2020 年,这只是没有黑客的停止视频的有效解决方案。

I end up with:

我最终得到:

function play_youtube_in_modal(src) {
    // enablejsapi = for enabling to stop on hide.bs.modal
    src += "?autoplay=1&modestbranding=1&rel=0&fs=1&enablejsapi=1";
    $("#modal_youtube_iframe").attr("src", src);

    //show
    $("#modal_youtube").modal("show");
}

// stop playing the youtube video when I close the modal
$('#modal_youtube').on('hide.bs.modal', function (e) {
    $('#modal_youtube_iframe').each(function(){
        this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
    });
})

回答by benembery

Here is a JS Fiddle.

这是一个JS Fiddle

I've added a bit of progressive enhancement so were the JS to fail you would be taken to the YouTube video in this case.

我添加了一些渐进增强功能,因此在这种情况下,如果 JS 失败,您将被带到 YouTube 视频。

The link requires a data-video-embed and a target to where we are going to be adding the video every thing else should just work. The event in the example is for Bootstrap 3 modal if you are using 2.X it will just be 'hide'.

该链接需要一个数据视频嵌入和一个目标,我们将在何处添加视频,其他一切都应该可以正常工作。示例中的事件适用于 Bootstrap 3 模式,如果您使用的是 2.X,它将只是“隐藏”。

$('[data-provider="modal-video"]')
   .on('click', function (evt) {
      evt.preventDefault();
      var $target = $(evt.currentTarget),
          videoSrc = $target.data('video-embed'),
          $modal = $($target.data('target'));

      $modal
        .find('iframe').attr('src', videoSrc)
        .end()
        .on('hide.bs.modal', function () {
            $(this)
                .off('hide.bs.modal')
                .find('iframe').attr('src', '');
        })
        .modal('show');
});