问题
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