Youtube iframe API仅适用于第一个

时间:2016-08-17 10:00:57

标签: jquery youtube-iframe-api

我在这里尝试了一些没有成功的解决方案。

Youtube视频位于隐藏的div中。

单击按钮并显示视频,但是当我单击“暂停”按钮时,div需要再次隐藏(强制和工作)

第二次,我点击播放视频按钮,视频出现,但自动播放既没有暂停也没有触发隐藏事件。

为什么?

JSFIDDLE:https://jsfiddle.net/u19ut5gt/6/

HTML

<div id="fw16-liam">
            <div class="fw16-button playvideo">Play Video</div>
            <div id="liam-video"><div id="ytplayer"></div></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

的Javascript

$("#fw16-liam .playvideo").click(function(){
                $("#liam-video").fadeIn(1000);
                runPlayer( '0m9hYRUV920' );
            });

            if(document.getElementById('iframe_api') === null){
                var tag = document.createElement('script');
                tag.src = "https://www.youtube.com/iframe_api";
                tag.id = "iframe_api";
                var firstScriptTag = document.getElementsByTagName('script')[0];
                firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
            }

            function runPlayer( video_id ){
                var player;
                player = new YT.Player('ytplayer', {
                    playerVars: {
                        autoplay: 1,
                        html5: 1,
                        controls: 1,
                        showsearch: 0,
                        showinfo: 0,
                        loop: 1,
                        fs: 0
                    },
                    height: '300',
                    width: '487',
                    videoId: video_id,
                    events: {
                        onStateChange: function (event) {   
                            // Loop after video end
                            if(event.data === YT.PlayerState.ENDED){
                                event.target.playVideo();
                            }           

                            // If user, pause video, then this hide.
                            if(event.data == 2){
                                event.target.stopVideo();
                                $("#liam-video").fadeOut(200);
                            }
                        }
                    }
                });
            }

CSS

.playvideo{width:112px; height: 37px; color: white;}
.fw16-button {cursor: pointer;cursor: hand; background-color: red;}
#liam-video{display:none; background: #9e7969; width: 487px; height:677px; position: relative; left: 0px; top: 20px; border: none;}
#liam-video iframe{border:none;}

1 个答案:

答案 0 :(得分:1)

您应该只初始化player一次。下次需要重现视频时,只需致电playVideo即可。在runPlayer函数中,尝试以下内容:

var player;
function runPlayer( video_id ){
  if(player) {
    player.playVideo();
    return player;
  }
  player = new YT.Player('ytplayer', {
    ...
  }
}

结帐https://developer.android.com/training/basics/fragments/communicating.html