jQuery 当 Bootstrap Modal 关闭时,YouTube 视频仍在播放

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22613303/
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-08-27 02:00:41  来源:igfitidea点击:

Youtube Video Still Playing When Bootstrap Modal Closes

jqueryyoutubemodal-dialog

提问by Stephen Tamlin

I am creating a website with bootstrap that can be found here - http://www.branchingouteurope.com/digital-spark-testing/

我正在创建一个带有引导程序的网站,可以在这里找到 - http://www.branchingouteurope.com/digital-spark-testing/

If you select the video image you'll see a modal window open a youtube video. The problem I have is that when the modal window is closed the video keeps playing. I want this video to stop when the modal window is closed.

如果您选择视频图像,您将看到一个打开 YouTube 视频的模式窗口。我遇到的问题是,当模态窗口关闭时,视频会继续播放。我希望这个视频在模态窗口关闭时停止。

I've looked online and read many solutions however none seem to work. Here is the mark up...

我在网上查看并阅读了许多解决方案,但似乎都没有。这里是标记...

<span class="main_video">
<div data-toggle="modal" data-target="#myModal" style="cursor:pointer">
<img src="img/master/video.fw.png" height="81%" width="60%" alt="Digital Spark Video"/>
</div>
</span>

<div class="modal-dialog">
<div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
  </div>
  <div class="modal-body">
  <iframe width="100%" height="100%" src="//www.youtube.com/embed/sIFYPQjYhv8?rel=0" frameborder="0" allowfullscreen></iframe>
  </div>
</div>

`

`

采纳答案by dizarter

Testing here in FireFox 26.0, works as expected. When I either close the Modal or click outside of it and then re-open it - video is back to start and stopped.

在 FireFox 26.0 中进行测试,按预期工作。当我关闭模态或单击它的外部然后重新打开它时 - 视频重新开始并停止。

EDIT 1

编辑 1

Reproduced in Chrome, the video indeed keeps playing after the Modal is closed.

在Chrome中重现,视频确实在Modal关闭后继续播放。

Try these already answered questions

试试这些已经回答的问题

Stop a youtube video with jquery?

使用 jquery 停止 YouTube 视频?

Twitter Bootstrap Modal stop Youtube video

Twitter Bootstrap Modal 停止 Youtube 视频

The best way seems to be to use YouTube API to stop the video. Answer that uses this method is available in the questions above.

最好的方法似乎是使用 YouTube API 来停止视频。使用此方法的答案可在上述问题中找到。

EDIT 2

编辑 2

This solution seems to be working.

这个解决方案似乎有效。

First, get the JS from this post: YouTube iframe API: how do I control a iframe player that's already in the HTML?and include it on the page.

首先,从这篇文章中获取 JS:YouTube iframe API:如何控制已经在 HTML 中的 iframe 播放器?并将其包含在页面上。

Add this JS after you have loaded the above script (just before the closing body tag)

在加载上述脚本后(就在结束正文标记之前)添加此 JS

<script type="text/javascript">
    $('#myModal').on('hidden.bs.modal', function () {
        callPlayer('yt-player', 'stopVideo');
    });
</script>

You will also need to add an ID to the div containing the iframe, as below

您还需要向包含 iframe 的 div 添加一个 ID,如下所示

<div class="modal-body" id="yt-player">
    <iframe src="//www.youtube.com/embed/sIFYPQjYhv8?rel=0&enablejsapi=1" allowfullscreen="" width="100%" frameborder="0" height="100%"></iframe>
</div>

回答by Cloudkiller

Here's a little bit lighter of an answer based on dizarter's version and one of the solutions he links to.

这是基于 dizarter 的版本和他链接到的解决方案之一的答案稍微轻一点。

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

回答by Bruno Ribeiro

take a look at my code I did not need to use any API

看看我的代码我不需要使用任何 API

// on preview show iframe
$('#myModalPrev').on('show.bs.modal', function (e) {
  var idVideo = $(e.relatedTarget).data('id');
  $('#myModalPrev .modal-body').html('<iframe width="100%" height="400px" src="https://www.youtube.com/embed/' + idVideo + '?autoplay=true" frameborder="0" allowfullscreen></iframe>');
});
//on close remove
$('#myModalPrev').on('hidden.bs.modal', function () {
   $('#myModalPrev .modal-body').empty();
});

HTML

HTML

<a href="#" data-id="5Kp_1Vq6pRg" data-target="#myModalPrev" data-toggle="modal">Abrir Modal</a>
    <div class="modal fade" id="myModalPrev" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <h4 id="myModalLabel" class="semi-bold">Visualizar <strong>Marca</strong>.</h4>
                    </div>
                    <hr>
                    <div class="modal-body">
                        Modal Content
                    </div>
                    <hr>
                    <div class="modal-footer">
                        <button type="button" data-dismiss="modal" class="btn btn-primary"><i class="fa fa-times"></i> Fechar</button>               
                    </div>
                </div>
            </div>
        </div>

Demo :https://jsfiddle.net/o0ftdvs1/

演示:https : //jsfiddle.net/o0ftdvs1/

回答by Danny Mahoney

Here is an alternative to CloudKiller's answer that actually works with autoplay, just change .attrto .removeAttrlike so:

这是 CloudKiller 答案的替代方案,它实际上适用于自动播放,只需更改.attr.removeAttr

jQuery('#myModal iframe').removeAttr("src", jQuery("#myModal iframe").removeAttr("src"));

But an even more minified/simplified version of this is to simply replace the srcwith an empty value:

但更缩小/简化的版本是简单地用src空值替换:

$('#myModal iframe').attr('src', '');

So the only code that you need to add for this to work is:

因此,您需要为此添加的唯一代码是:

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

回答by ?ukasz

This solution works fine for Boostrap 4. It supports many different modals on the same page without specifying modal id. Here is the demo http://jsfiddle.net/hxtpoe/6k09f4x2/

此解决方案适用于 Boostrap 4。它支持同一页面上的许多不同模态,而无需指定模态 ID。这是演示http://jsfiddle.net/hxtpoe/6k09f4x2/

$('.modal').on('hide.bs.modal', function() {
     var memory = $(this).html();
     $(this).html(memory);
});

回答by Perry

And if like me you want the video's to autoplay, then getting them to stop when you click close on the Bootstrap modal you need to do something like this:

如果像我一样希望视频自动播放,那么当您在 Bootstrap 模式上单击关闭时让它们停止,您需要执行以下操作:

$('.modal-iframe-youtube').click(function (e) {
        e.preventDefault();
        var sitetypeHref = $(this).attr('href');
        var sitetypeHrefAuto = sitetypeHref + "?autoplay=1"
        //sitetypeHref = sitetypeHref.replace('watch?v=', 'v/');
        $('#modal-window-iframe-youtube').on('shown.bs.modal', function () {
            var iFrame = $(this).find("iframe");
            iFrame.attr("src", sitetypeHrefAuto);
        });
        $("#modal-window-iframe-youtube").on('hidden.bs.modal', function () {
            var iFrame = $(this).find("iframe");
            iFrame.attr("src", sitetypeHref);
        });
        $('#modal-window-iframe-youtube').modal({ show: true });
    });

Notice that I am adding the "?autoplay=1" arg dynamically. Hope that helps someone.

请注意,我正在动态添加“?autoplay=1”参数。希望能帮助某人。

回答by Anand Deep Singh

To write efficient code, first of all we need to check on DOM ready that iframe is exist or not if exist so go to next level otherwise don't do anything. I have used catching also.

要编写高效的代码,首先我们需要检查 DOM 是否准备好 iframe 是否存在,如果存在,则转到下一级,否则不要做任何事情。我也用过捕捉。

$("#myModal").on("hidden.bs.modal", function() {

    var _this = this,
        youtubeSrc = $(_this).find("iframe").attr("src");

    if($(_this).find("iframe").length > 0){                     // checking if there is iframe only then it will go to next level
        $(_this).find("iframe").attr("src", "");                // removing src on runtime to stop video
        $(_this).find("iframe").attr("src", youtubeSrc);        // again passing youtube src value to iframe
    }
}

回答by parouden

This is a solution that worked for me (a bit hacky though):

这是一个对我有用的解决方案(虽然有点hacky):

First, I wrapped my iframewith a divnamed "VideoId"like this:

首先,我用名为“VideoId”div包裹我的iframe,如下所示:

<div id="VideoId" style="position: relative; padding: 25px; height: 0;">
    <iframe style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;"
    src="//www.youtube.com/etc..."
    frameborder="0" 
    allowfullscreen>
    </iframe>
</div>

Then i made this function:

然后我做了这个功能:

function CloseVideo(){
    document.getElementById("VideoId").innerHTML="&nbsp;";
};

And finally, on the closing my Panel button (it was a modal in my case) i added an oncklick event calling my function, like this:

最后,在关闭我的面板按钮(在我的情况下它是一个模式)我添加了一个调用我的函数的 oncklick 事件,如下所示:

<button type="button" class="btn pull-right" onclick="CloseVideo();" data-dismiss="modal">Back</button>

Of course, if you want to call it again, you have to refill the contents of VideoIdwith javascript as follows:

当然,如果你想再次调用它,你必须用javascript重新填充VideoId的内容,如下所示:

document.getElementById("VideoId").innertHTML=
 '<iframe style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;"+
    'src="//www.youtube.com/etc..."'+
    'frameborder="0"'+ 
    'allowfullscreen>'+
    '</iframe>';

It works perfectly in Chrome, Firefox, IE and Opera.

它在 Chrome、Firefox、IE 和 Opera 中完美运行。

P.S. I tried to empty the divdirectly from the onclick calling, but it kept reporting a missing bracket, - i don't know why...

PS我试图直接从onclick调用中清空div,但它一直报告缺少括号, - 我不知道为什么......

回答by patelarpan

you can use youtube API to Stop(player.stopVideo()) or pause (player.pauseVideo()) your video. here the example code.

您可以使用 youtube API 来停止 (player.stopVideo()) 或暂停 (player.pauseVideo()) 您的视频。这里是示例代码。

HTML

HTML

Place this markup in your modal content.

将此标记放在您的模态内容中。

<div id="player"></div>

Load youtube API and initialize player

加载 youtube 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);
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('player', {
          height: '390',
          width: '640',
          videoId: 'N8c20YDDHd8',
        });
      }

Stop or pause Video on modal close

在模态关闭时停止或暂停视频

     $('#videoModal').on('hidden.bs.modal', function (e) {
        // player.stopVideo();
        player.pauseVideo()
    });

回答by sandman8888

If you have several video modals, the best way to handle it without resorting to use the api is this:

如果您有多个视频模态,那么在不使用 api 的情况下处理它的最佳方法是:

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

This goes through all the iframes on your modals and resets them, instead of overwriting the src of all your iframes to the first video on your modal set.

这会遍历模态上的所有 iframe 并重置它们,而不是将所有 iframe 的 src 覆盖到模态集上的第一个视频。