說明如何使用 Youtube Player Iframe API 製作網頁全螢幕背景播放的效果。
準備 HTML
準備如以下的 HTML,會使用到 data 屬性來取得 YouTube 影片的 id。
<div id="youtubeEmbed" class="bg_video" data-video-id="Tb1lR8Z5oM"></div>
撰寫 CSS
.bg_video, iframe { position: absolute; top: 50%; left: 50%; -webkit-transform: translate(-50%, -50%); transform: translate(-50%, -50%); width: 100vw; height: 56.25vw; /* 9/16*100 = 56.25 */ min-height: 100vh; min-width: 177.77vh; /* 16/9*100 = 177.77 */ } iframe { opacity: 0; } iframe.loaded { opacity: 1; }
javascript 的部分
// Get element var youtubeEmbedElement = document.getElementById("youtubeEmbed"); // Add YouTube API 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; var videoId = youtubeEmbedElement.dataset.videoId; var startSeconds = 184; var endSeconds = 210; onYouTubeIframeAPIReady = function () { player = new YT.Player("youtubeEmbed", { videoId: videoId, // YouTube Video ID playerVars: { autoplay: 1, // Auto-play the video on load autohide: 1, // Hide video controls when playing disablekb: 1, controls: 0, // Hide pause/play buttons in player showinfo: 0, // Hide the video title modestbranding: 1, // Hide the Youtube Logo loop: 1, // Run the video in a loop fs: 0, // Hide the full screen button rel: 0, enablejsapi: 1, start: startSeconds, end: endSeconds }, events: { onReady: function (e) { e.target.mute(); e.target.playVideo(); }, onStateChange: function (e) { if (e.data === YT.PlayerState.PLAYING) { document.getElementById("youtubeEmbed").classList.add("loaded"); } if (e.data === YT.PlayerState.ENDED) { // Loop from starting point player.seekTo(startSeconds); } } } }); };
來源:
Fullscreen Background Video Using YouTube Player API