问题描述:

I am creating a website with bootstrap that can be found here - 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.

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>

`

网友答案:

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.

EDIT 1

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

Try these already answered questions

Stop a youtube video with jquery?

Twitter Bootstrap Modal stop Youtube video

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.

EDIT 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.

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

<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

<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>
网友答案:

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

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

take a look at my code I did not need to use any 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();
});
网友答案:

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:

$('.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.

网友答案:

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

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

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

$('#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', '');
});
网友答案:

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.

$("#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
    }
}
网友答案:

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

First, I wrapped my iframe with a div named "VideoId" like this:

<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:

<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 VideoId with javascript as follows:

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.

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

网友答案:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example of Embedding YouTube Video inside Bootstrap Modal</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<style type="text/css">
    .bs-example{
        margin: 20px;
    }
    .modal-content iframe{
        margin: 0 auto;
        display: block;
    }
</style>
<script type="text/javascript">
$(document).ready(function(){
    /* Get iframe src attribute value i.e. YouTube video url
    and store it in a variable */
    $("#myModal").modal('show');
    var url = $("#cartoonVideo").attr('src');

    /* Assign empty url value to the iframe src attribute when
    modal hide, which stop the video playing */
    $("#myModal").on('hide.bs.modal', function(){
        $("#cartoonVideo").attr('src', '');
    });

    /* Assign the initially stored url back to the iframe src
    attribute when modal is displayed again */
    $("#myModal").on('show.bs.modal', function(){
        $("#cartoonVideo").attr('src', url);
    });
});
</script>
</head>
<body>
<div class="bs-example">
    <!-- Button HTML (to Trigger Modal) -->
    <a href="#myModal" class="btn btn-lg btn-primary" data-toggle="modal">Launch Demo Modal</a>

    <!-- Modal HTML -->
    <div id="myModal" 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>
                    <h4 class="modal-title">YouTube Video</h4>
                </div>
                <div class="modal-body">
                    <iframe id="cartoonVideo" width="560" height="315" src="https://www.youtube.com/embed/LGWqUVFrfU4?autoplay=1&modestbranding=1&autohide=1&showinfo=0&controls=0" frameborder="0" allowfullscreen></iframe>
                </div>
            </div>
        </div>
    </div>
</div>     
</body>
</html>     

use this code check once again. it works for me nicely.

相关阅读:
Top