模态窗口中的YouTube播放器

时间:2018-08-17 17:35:59

标签: jquery twitter-bootstrap youtube modal-dialog

我希望我的页面将div作为模式显示,然后播放YouTube视频。我能够使视频按预期播放(下面的代码),但是当我通过过滤操作切换到隐藏的div时,在页面加载时隐藏的div不会将data-src值传递给模式。我尝试通过jQuery分离模式并执行insertAfter(),但是Bootstrap模式保持相同的data-src值。

两个问题:1)YouTube是否有一种本机嵌入到模式窗口的方法? 2)关于DOM,我缺少什么?它如何保持传递给模态的初始data-src值?

链接的HTML(点击):

<div class="video-btn" data-toggle="modal" data-src="https://www.youtube.com/embed/Sa_5fh_OFcc" data-target="#myModal">Overview</div>
<div class="video-btn" data-toggle="modal" data-src="https://www.youtube.com/embed/TBCyYTNBObI" data-target="#myModal">Installation Instructions</div>

模式窗口的HTML:

<!-- Modal for video-->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">&times;</span>
</button>        
<!-- 16:9 aspect ratio -->
<div class="embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" type="text/html" width="640" height="390" src="" id="video"   frameborder="0"></iframe>
</div>
</div>
</div>
</div>
</div>

jQuery获取data-src值(YouTube链接)并创建视频对象

$('.video-btn').click(function()
{
$videoSrc = $(".video-btn").data( "src" );
});

JavaScript / jQuery打开模式并播放视频:

    // when the modal is opened autoplay it  
    $('#myModal').on('shown.bs.modal', function (e)
    {
        // set the video src to autoplay and not to show related video. 
        console.log($("#video").attr('src',$videoSrc));

        //$("#video").attr('src',$videoSrc + "?rel=0&amp;showinfo=0&amp;modestbranding=1&amp;autoplay=1&amp;controls=0&amp'enablejsapi=1" ); 
    });//#myModal show

    // stop playing the youtube video when I close the modal
    $('#myModal').on('hide.bs.modal', function (e)
    {
        // a poor man's stop video
        $("#video").attr('src',$videoSrc); 
        //remove modal from DOM
        //$("#myModal").detach();
    });//#myModal close

1 个答案:

答案 0 :(得分:1)

尝试使用此插件https://sorgalla.com/lity/。使用非常简单

<a href="//www.youtube.com/watch?v=XSGBVzeBUbk" data-lity>iFrame Youtube</a>

,然后只需添加此脚本即可。

var lightbox = lity('//www.youtube.com/watch?v=XSGBVzeBUbk');
$(document).on('click', '[data-lightbox]', lity);