隐藏弹出窗口时暂停/停止YouTube视频

时间:2014-04-03 11:40:44

标签: javascript jquery youtube

我一直在研究找到一个答案,但似乎无法弄清楚当隐藏弹出窗口时如何让这个youtube视频停止播放。这是我的代码......

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>

    <script type="text/javascript">
    $(document).ready(function() {  

            var id = '#dialog';

            //Get the screen height and width
            var maskHeight = $(document).height();
            var maskWidth = $(window).width();

            //Set heigth and width to mask to fill up the whole screen
            $('#mask').css({'width':maskWidth,'height':maskHeight});

            //transition effect     
            $('#mask').fadeIn(1000);    
            $('#mask').fadeTo("slow",0.8);  

            //Get the window height and width
            var winH = $(window).height();
            var winW = $(window).width();

            //Set the popup window to center
            $(id).css('top',  winH/2-$(id).height()/2);
            $(id).css('left', winW/2-$(id).width()/2);

            //transition effect
            $(id).fadeIn(2000);     

        //if close button is clicked
        $('.window .close').click(function (e) {
            //Cancel the link behavior
            e.preventDefault();

            $('#mask').hide();
            $('.window').hide();
        });     

        //if mask is clicked
        $('#mask').click(function () {
            $(this).hide();
            $('.window').hide();
        });

    });
    </script>

    </head>

<body>

<div id="boxes">
    <div id="dialog" class="window">

    <a href="#" class="close"><img src="exit_button.png" width="25" height="25" style="float:right;" /></a>

    <br />
    <br />

    <iframe width="853" height="480" src="http://www.youtube.com/embed/9SgIIlloQ5U?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

    </div>
    <!-- Mask to cover the whole screen -->
    <div id="mask"></div>
</body>
</html>

我是一个javascript新手,可能会对你很明显,但我只需要一个简单的解决方案来使这项工作正常运行。

1 个答案:

答案 0 :(得分:0)

您需要使用YouTube API生成播放器并使用JavaScript从您的页面控制它。完整的文档在这里:https://developers.google.com/youtube/js_api_reference

基本上你需要做的是使用这个URL而不是iframe将视频作为对象嵌入到页面中:

https://www.youtube.com/v/9SgIIlloQ5U?version=3&enablejsapi=1

这会加载所选的播放器和视频并启用JavaScript API。然后,您可以使用这些方法来控制播放器:在需要启动视频时触发player.playVideo(),在需要暂停时触发player.pauseVideo()

您可以使用API​​做很多其他事情 - 所有信息都在提供的链接中。