Youtube 视频不会在 Bootstrap Modal 关闭时停止播放



我的网站上有一个引导模式,当YouTube视频弹出时会自动播放它。当我单击右上角的 X 按钮时,模式关闭,视频停止播放。但是,当我通过在视频弹出窗口外单击来关闭模式时,视频一直在后台播放。另外,当我单击启动按钮时,视频会自动播放。

如何使视频在视频弹出窗口外单击时停止播放?

以下是我在 youtube 视频中模态的 HTML 代码:

<button id="launch-button" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#myModal" data-theVideo="http://www.youtube.com/embed/loFtozxZG0s"><i class="fa fa-play"></i></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-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                </div>
                <!-- BODY -->
                <div class="modal-body">
                    <iframe width="100%" height="350" src="" frameborder="0"></iframe>
                </div>
            </div>
        </div>
    </div>

以下是我的JavaScript代码:

function autoPlayYouTubeModal(){
    var trigger = $("body").find('[data-toggle="modal"]');
    trigger.click(function() {
        var theModal = $(this).data( "target"),
            videoSRC = $(this).attr( "data-theVideo"),
            videoSRCauto = videoSRC+"?autoplay=1" ;
        $(theModal+' iframe').attr('src', videoSRCauto);
        $(theModal+' button.close').click(function () {
            $(theModal+' iframe').attr('src', videoSRC);
        })
    })
}
$(document).ready(function(){
    autoPlayYouTubeModal();
})

感谢您的帮助!

我能够弄清楚,以防万一有人遇到同样的问题。

我补充说:

$('#myModal').on('hidden.bs.modal', function (e) {
    // do something...
})

到我的JavaScript代码。最终结果如下所示:

function autoPlayYouTubeModal(){
    var trigger = $("body").find('[data-toggle="modal"]');
    trigger.click(function() {
        var theModal = $(this).data( "target"),
            videoSRC = $(this).attr( "data-theVideo"),
            videoSRCauto = videoSRC+"?autoplay=1" ;
        $(theModal+' iframe').attr('src', videoSRCauto);
        $(theModal+' button.close').click(function () {
            $(theModal+' iframe').attr('src', videoSRC);
        })
        $('#myModal').on('hidden.bs.modal', function (e) { // new code
            $(theModal+' iframe').attr('src', videoSRC);
        })
    })
}

希望这有帮助!

最新更新