hide div after YouTube video ends

ε祈祈猫儿з 提交于 2019-12-25 05:18:23

问题


I am working on a simple one page website for a friend, which contains a YouTube video embed. I'm not very familiar with the YouTube API, but I got the follow to work (see below). What do I need to change so that when the video completes the player disappears and a DIV is loaded.

<div id="player"></div>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;

function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: 'y-y8v4BClZE',
        events: {
            'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
        }
    });
}

function onPlayerReady(event) {
    event.target.playVideo();
}

var done = false;

function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
        setTimeout(stopVideo, 720000);
        done = true;
    }
}

function stopVideo() {
    player.stopVideo();
}
</script>

回答1:


Assuming your script works, you should just do :

function stopVideo() {
    player.stopVideo();
    document.getElementById("player").style.display = "none";
}

As for the detection of the end of the video, you should do :

function onPlayerStateChange(event) {        
    if(event.data === YT.PlayerState.ENDED) {          
        stopVideo();
    }
}


来源:https://stackoverflow.com/questions/25184549/hide-div-after-youtube-video-ends

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!