YouTube IFrame API埋め込み動画を表示させる方法
<div class="mv_bg " id="youtube" >
</div>
<script>
if(!navigator.userAgent.match(/(iPhone|iPod|Android)/)){
// 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);
// YouTubeの埋め込み
function onYouTubeIframeAPIReady() {
ytPlayer = new YT.Player(
'youtube', // 埋め込む場所をIDで設定
{
videoId: 'YouTubeのID', // YouTubeのIDを指定
width: 1920,
height: 1080,
playerVars: {
controls: 0,
autoplay: 1,
showinfo: 0,
fs: 0,
rel: 0,
wmode: 'transparent',
},
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
}
);
}
function onPlayerReady(event) {
event.target.seekTo(0);
// event.target.playVideo();
event.target.mute();
event.target.setPlaybackQuality('hd1080');
}
function onPlayerStateChange(e) {
var ytStatus = e.target.getPlayerState();
if (ytStatus == YT.PlayerState.ENDED) {
ytPlayer.seekTo(0);
// ytPlayer.playVideo();
ytPlayer.mute();
}
}
// 上下左右に出てくる黒帯を非表示
var $WIN = $(window); // ブラウザのウインドウを取得する
// var WIN_H;
// var win_W;
function yt_screen_retio() {
// 上下左右の縦横比を調節する関数
const WIN_H = $WIN.height(); // windowの高さを取得
const WIN_W = $WIN.width(); // windowの幅を取得
const screen_switch = 0.5625; // youtubeの縦横比16:9=>9/16した値
const screen_ratio = WIN_H / WIN_W; // windowの高さの値/windowの幅の値
const ratio_H = WIN_H / screen_switch; // windowの高さ/縦横比の値
const ratio_W = WIN_W * screen_switch; // windowの幅*縦横比の値
if (screen_ratio > screen_switch) {
// windowの高さの値/windowの幅の値>youtubeの縦横比16:9=>9/16した値
$("#youtube").css({
height: "110%",
width: ratio_H,
"margin-top": -50,
"margin-left": -ratio_H / 2,
// "margin-left": -ratio_H,
left: "50%",
top: "0"
});
} else {
$("#youtube").css({
width: "100%",
height: ratio_W + 100,
"margin-top": -50 +(-ratio_W / 2),
"margin-left": "0",
top: "50%",
left: "0"
});
}
}
$WIN.on("resize", function() {
// windowの縦横比が変わったら実行する処理
yt_screen_retio();
});
$(function() {
// domツリーが構築したら実行する処理
yt_screen_retio();
});
}
</script>