今天研究了一下youtube的api!
這是一個讓影片置中,自動播放,循環播放,可以隱藏標題與點擊的小例子。
<!DOCTYPE html>
<html>
<style>
.cover {
overflow: hidden;
height: 800px;
left: 0;
right: 0;
top: 0;
bottom: 0;
position: relative;
}
#player {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
pointer-events: none;
}
</style>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div class="cover">
<div id="player"></div>
</div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
videoId: 'VjFexIwgcgw', // YouTube 影片ID
width: '1920', // 播放器寬度 (px)
height: '1200', // 播放器高度 (px)
playerVars: {
autoplay: 1, // 自動播放影片
controls: 0, // 顯示播放器
showinfo: 0, // 隱藏影片標題
modestbranding: 0, // 隱藏YouTube Logo
loop: 1, // 重覆播放
playlist: 'VjFexIwgcgw', // 當使用影片要重覆播放時,需再輸入YouTube 影片ID
fs: 0, // 隱藏全螢幕按鈕
cc_load_policty: 0, // 隱藏字幕
iv_load_policy: 3, // 隱藏影片註解
autohide: 0, // 影片播放時,隱藏影片控制列
},
events: {
onReady: function (e) {
e.target.mute(); //播放時靜音
e.target.playVideo(); //強制播放(手機才會自動播放,但僅限於Android)
}
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
參考:
https://developers.google.com/youtube/player_parameters#autoplay