Twitter Bootstrap Modal stop Youtube video



我对javascript很陌生,并尝试使用Twitter引导程序来快速启动和运行一个好看的网站。 我知道这与jquery有关,但是当我按下关闭按钮或关闭图标时,我不确定如何停止我的视频。

有人可以解释一下如何让我的视频停止播放,因为即使我关闭窗口,我仍然可以在后台听到它。

<!-- Button to trigger modal -->
    <a href="#myModal" role="button" class="btn" data-toggle="modal"><img src="img/play.png"></a>
<!-- Modal -->
  <div id="myModal" class="modal hide fade" tabindex="-1" role=labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria>×</button>
      <h3 id="myModalLabel">I am the header</h3>
    </div>
    <div class="modal-body">
      <p><iframe width="100%" height="315" src="http:com/embed/662KGcqjT5Q" frameborder="0" allowfullscreen></iframe></p>
    </div>
    <div class="modal-footer">
      <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    </div>
  </div>

我知道我晚了 2+ 年,但从那时起,发生了一些变化,使用 B3 开箱即用的新方法是:

$("#myModal").on('hidden.bs.modal', function (e) {
    $("#myModal iframe").attr("src", $("#myModal iframe").attr("src"));
});

享受引导的乐趣!

有一个很好的正确方法可以做到这一点 - 请参阅这篇文章的批准答案中的评论。

不过,我自己第一次无法做到这一点,而且很着急,所以我做了一个相当可怕的黑客代码来解决问题。

此代码段"刷新"嵌入 iframe 的 src,使其重新加载:

jQuery(".modal-backdrop, #myModal .close, #myModal .btn").live("click", function() {
        jQuery("#myModal iframe").attr("src", jQuery("#myModal iframe").attr("src"));
});

如果有人仍然有问题,请尝试以下操作,它对我有用:

$(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);
        });
    });
});

这是我发现的一种简单方法,可以在模态窗口中播放视频,然后在关闭时停止播放。

当显示模态时,使用 .html 将包含视频的 iFrame 加载到模态正文中,然后在隐藏模态正文时将其替换为任何内容。

$('#myModal').on('show', function () { 
 $('div.modal-body').html('YouTube iFrame goes here');  
});
$('#myModal').on('hide', function () {
 $('div.modal-body').html('');
});

下面是一个 jsfiddle 示例:

http://jsfiddle.net/WrrM3/87/

在这里,我概括了@guillesalazar的答案。

这将重置任何引导模式中的任何 iFrame(当模式关闭时):

$(function(){
  $("body").on('hidden.bs.modal', function (e) {
    var $iframes = $(e.target).find("iframe");
    $iframes.each(function(index, iframe){
      $(iframe).attr("src", $(iframe).attr("src"));
    });
  });
});

将其添加到您的布局中,您就设置好了。

更新:为具有多个 iFrame 的模态修改了代码。

您应该先清空 iframe src,然后再设置它。

所以我的工作答案:

$('#myModal').on('hidden.bs.modal', function () {
    var src = $(this).find('iframe').attr('src');
    $(this).find('iframe').attr('src', '');
    $(this).find('iframe').attr('src', src);
});

十月, 2014.对于引导程序 3。

这是我的解决方案,它使用引导事件调用解决了以下问题:

  1. 显示模态时自动播放影片
  2. 隐藏模态时停止动画

态内的HTML轮播,第一个活动项目是iframe视频

<button class="btn btn-primary" data-toggle="modal" data-target="#myModal">Modal</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <div id="myCarousel" class="carousel slide carousel-fade" data-ride="carousel">
                    <div class="carousel-inner" role="listbox">
                        <div class="item active">
                            <div class="fill">
                                <iframe id="videoIframe" width="100%" height="100%" src="https://www.youtube.com/embed/UVAjm8b7YFg?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

显示模态时Javascript自动播放,然后重置URL并将其再次应用于iframe src

$('#myModal').on('show.bs.modal', function() {
    $("#videoIframe")[0].src += "&autoplay=1";
});
$('#myModal').on('hidden.bs.modal', function(e) {
    var rawVideoURL = $("#videoIframe")[0].src;
    rawVideoURL = rawVideoURL.replace("&autoplay=1", "");
    $("#videoIframe")[0].src = rawVideoURL;
});

这个完美地做到了:

$("#myModal").on("hidden.bs.modal", function(t) {
   var o = $(t.target).find("iframe");
   o.each(function(t, o) {
      $(o).attr("src", $(o).attr("src"))
   });
});

但是,如果您希望它在模态打开时启动/关闭时停止,请使用以下代码:

但请确保在 src 中添加enablejsapi=1,例如:

<iframe src="https://www.youtube.com/embed/YOUR_VIDEO_CODE?rel=0&amp;controls=0&amp;showinfo=0&enablejsapi=1" frameborder="0" allowfullscreen></iframe>

function playStopVideo() {
    var youtubeFunc ='';
    var outerDiv = $("#myModal");
    var youtubeIframe = outerDiv.find("iframe")[0].contentWindow;
    outerDiv.on('hidden.bs.modal', function (e) {
        youtubeFunc = 'stopVideo';
        youtubeIframe.postMessage('{"event":"command","func":"' + youtubeFunc + '","args":""}', '*');
    });
    outerDiv.on('shown.bs.modal', function (e) {
        youtubeFunc = 'playVideo';
        youtubeIframe.postMessage('{"event":"command","func":"' + youtubeFunc + '","args":""}', '*');
    });
}
playStopVideo();

比所有这些答案更简单的方法是替换整个 src。这适用于所有模态,您可以根据需要调整 iframe 类。

$('.modal').on('hidden.bs.modal', function(e) {
    var closestIframe = $(e.currentTarget).find('iframe');
    var rawVideoURL = $("iframe")[0].src;
    closestIframe[0].src = "";
    closestIframe[0].src = rawVideoURL;
  });

在事件hide.bs.modal以引导模式重新加载任何 iframe。

为重置后修复 iframe 渲染而添加setTimeout延迟src

$('.modal').on('hidden.bs.modal', function (event){
    let iframes = event.target.getElementsByTagName('iframe');
    for (let i = 0; i < iframes.length; i++) {
        let src_tmp = iframes[i].src;
        iframes[i].src = '';
        setTimeout(() => {
            iframes[i].src = src_tmp;
        }, 100);
    }
});

我使用了Ruslanas Balčiūnas和Nathan McFarland的答案的组合来编写一些对我来说效果很好的东西。

$('#myModal').on('hide',function(){
   $('.modal-body iframe').attr('src','');
});

所以基本上,当触发关闭模态事件时,这会将iframesrc 属性设置为无。简短而甜美。

我对此

的解决方案适用于Bootstrap 3和现代 YouTube embed格式如下。

假设您的视频嵌入在带有id="#video-modal"的标准Bootstrap 3 Modal中,这个简单的Javascript就可以完成这项工作。

$(document).ready(function(){
  $("#video-modal").on('hide.bs.modal', function(evt){
    var player = $(evt.target).find('iframe'),
        vidSrc = player.prop('src');
    player.prop('src', ''); // to force it to pause
    player.prop('src', vidSrc);
  });
});

我已经看到了涉及使用YouTube API的此问题的建议解决方案,但是如果您的网站不是https网站,或者您的视频是使用 YouTube 推荐的现代格式嵌入的,或者如果您设置了no-cookies选项,那么这些解决方案不起作用,您将获得"电视机到死频道"效果而不是您的视频。

我已经在我可以使用的每个浏览器上测试了上述内容,并且它运行非常可靠。

扩展上面 Guille 的答案,这是一个插入式功能,可与 Bootstrap 3(截至 8 月 14 日的最新版本 youtube)一起使用,并适用于一个页面中的多个视频/模态

$(".modal").on('hidden.bs.modal', function(e) {
    $iframe = $(this).find( "iframe" );
    $iframe.attr("src", $iframe.attr("src"));
}); 

有一个有很多视频的模态。 通过@guillesalazar更新了代码以关闭模态中的多个视频。

$("#myModal").on('hidden.bs.modal', function (e) {
            $("#myModal iframe").each(function () {
                $(this).attr("src", '');
            });
        });

7 年后,我们仍然需要解决这个问题。

我们找到了修复它的最佳方法(灵感来自 RobCalvert123 答案)

  jQuery(".modal-backdrop, .modal.open .close,.modal.open .btn").live("click", function() {  
         // Get iframe opened 
         var iframe_open = jQuery('.modal.open');     
         // Get src from opened iframe 
         var src = iframe_open.attr('src');
         // replace src by src to stop it that's the tips
        iframe_open.attr("src", src);
});

1.在您的主页上嵌入 Youtube (html)

将 Youtubediv 容器添加到您的网站:

<div id="ytplayer">This will be replaced with the Youtube iFrame</div>

添加 Youtube Javascript API (iFrame)

<script>
    // Ads Youtube JS API
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    // This function creates an <iframe> (and YouTube player) after the API code downloads.
    var player;
    function onYouTubeIframeAPIReady() {
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',
      videoId: 'ncif63mSZl4',
        WMode: 'transparent',
        wmode: 'opaque',
        playerVars: {
            'autoplay': 0,
            'controls': 0,
            'autohide':1,
            'rel':0,
            'showinfo': 0,
            'modestbranding': 1,
        },
      });
    }
   function stopVideo() {
    player.stopVideo();
   }
    
   function pauseVideo() {
    player.pauseVideo();
   }
    
   function playVideo(){
    player.playVideo();
   }
</script>

Controll with jQuery (Bootstrap Modal)


  // Open Modal and start Playing Youtube Video
  $("#myModalTrigger").click(function(){
    $("#video-modal").modal(); // opens up the Modal
    playVideo(); // Starts playing Video
  });
  // Stop Player on Modal hide
  $('#video-modal').on('hide.bs.modal', function (e) {
    stopVideo(); // stop player
  });
$('#myModal').on('hide', function () {
    $('#video_player')[0].stopVideo();
})

@guillesalazaar的答案只是我修复的前半部分,所以我觉得有必要分享我的情况,以防将来对某人有所帮助。 我也有一个嵌入式 youtube 视频,但我将我的设置为在使用autoplay=1加载帧时自动播放。 为了解决页面加载时的自动播放问题,我将我的 youtube 网址存储在一个变量中,该变量使用点击处理程序设置 iframe 源。 为了解决这个问题,我只是删除了属性源链接:

触发模式窗口的我的 URL:

   <div id="movieClick" class="text-center winner"> 
<a href="#" data-toggle="modal" data-keyboard="true" data-target="#movie">
    </div>

我的隐藏模态窗口div:

<div id="movie" class="modal fade" role="dialog" tabindex='-1'>
    <div class="modal-dialog">
<div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">They Live (1988)</h4>
    </div>
     <div class="modal-body">
        <iframe id="onscreen" width="100%" height="460px" src="" frameborder="0" allowfullscreen></iframe>
      </div>
</div>
</div>
</div>

我的JS:

$("#movieClick").click(function(){
var theLink  = "https://www.youtube.com/embed/Wp_K8prLfso?autoplay=1&rel=0";
document.getElementById("onscreen").src = theLink;
});

// really annoying to play in the Background...this disables the link
$("#movie").on('hidden.bs.modal', function (e) {
    $("#movie iframe").attr("src", '');
});
 //stop youtube video on modal close
$('.modal').on('hidden.bs.modal', function () {
    var iframVideo = $('.modal').find('iframe');
    $(iframVideo).attr("src", $(iframVideo).attr("src"));
});

我使用 HTML data-* 属性的 2 个或更多 Youtube 视频的解决方案。视频在模式打开和关闭时自动播放停止

<button data-url="https://www.youtube.com/embed/C0DPdy98e4c" data-toggle="modal" data-target="#mymodal">Video 1</button>
<button data-url="https://www.youtube.com/embed/ScMzIvxBSi4" data-toggle="modal" data-target="#mymodal">Video 2</button>
<!-- Modal -->
<div id="mymodal" class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-hidden="true">Close</button>
        </div>
        <div class="embed-responsive embed-responsive-16by9">
          <iframe class="embed-responsive-item" src="" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
        </div>
      </div>
    </div>
  </div>
</div>
$('.modal').on('show.bs.modal', function (event) {
  $(this).find('iframe').attr("src", $(event.relatedTarget).data('url') );
});
$('.modal').on('hidden.bs.modal', function (e) {
    $(this).find('iframe').attr("src", "");
});

下面是一个 Codepen 演示:https://codepen.io/danielblazquez/pen/oOxRJq

对于角度或动态 html,或者如果我们有多个 iframe,请使用如下

$("#myModal").on('hidden.bs.modal', function (e) {
  $("#myModal iframe").each(function(){
    $(this).attr("src", $(this).attr("src"));
  });
});

如果您有多个模态和许多视频,假设您在轮播上的每张幻灯片上都有一个模态,例如,您需要一些更动态的东西来关闭/停止可见幻灯片中的视频,而不是弄乱所有其他模态,请使用这个:

$(".modal").on('hidden.bs.modal', function (e) {
      $(this).find("iframe").attr("src", $(this).find("iframe").attr("src"));
  });

最新更新