youtubeでサイトにjavascriptAPIを使用して動画を埋め込むことがあります。
(基本的な使い方はこちら youtube>iframe 組み込みの YouTube Player API リファレンス)
そんな時レスポンシブを考えるとどうしても比率がおかしくなってしまうこともあるでしょう。
画面幅でサイズを変えることは簡単ですが、高さも変わってしまうと小さくなりすぎてしまうこともあります。
そこで画面幅で違う動画を読み込むように、youtubeに比率の違う動画をアップロードしてそれぞれ読み込むようにしてみました。要するに2つのyoutube動画をレスポンシブで切り替えるということです。
HTML
<div class="top_video_area"> <div class="top_video_inner"> <div id="player"></div> </div> </div>
まずはjavascriptでiframeを書き出すHTMLを作成します。
<div id=”player”></div>がそうです。
CSS
@keyframes opacity_show {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes opacity_out {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
.top_video_area {
width: 100vw;
height: 100vw;
margin: auto;
padding: 0px;
margin-bottom: 30px;
-webkit-animation: opacity_show 0.5s ease-in-out 0s 1 normal both running;
animation: opacity_show 0.5s ease-in-out 0s 1 normal both running;
}
@media screen and (min-width: 550px) {
.top_video_area {
max-width: 1080px;
max-height: 607.5px;
width: calc(100vw - (100vw - 100%));
height: calc(100vw * 9 / 16);
}
}
.top_video_inner {
width: 100%;
height: 100%;
display: block;
opacity: 1;
}
.opacity_str {
-webkit-animation: opacity_show 1s ease-in-out 0s 1 normal forwards running;
animation: opacity_show 1s ease-in-out 0s 1 normal forwards running;
}
.opacity_end {
-webkit-animation: opacity_out 4s ease-in-out 0s 1 normal forwards running;
animation: opacity_out 4s ease-in-out 0s 1 normal forwards running;
}CSSは画面幅によってインナーのサイズを変えます。
ブレークポイントはjavascriptと合わせます。
ついでにふわっと切り替わるアニメーションも入れてみました。
JS
function getScrollbarWidth() {
const scrollbarWidth = window.innerWidth - $(window).width();
return scrollbarWidth;
}
// 2. This code loads the IFrame Player API code asynchronously.
// IFrame Player API の読み込み
var tag = document.createElement('script');
tag.src = "//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.
let player;
let v_id = "";
let be_v_id = "";
let breakP = "550";//切り替えのサイズ(px)
let pcVideo = "pdg-XVW_19E";//PC用のyoutube動画ID
let smVideo = "B5Yic3VobKE";//スマホ用のyoutube動画ID
function getVideoId() {
let wi = getScrollbarWidth();
be_v_id = v_id;
if($(window).width() >= breakP - wi){
v_id = pcVideo;
}else{
v_id = smVideo;
}
}
function onYouTubeIframeAPIReady() {
getVideoId();
player = new YT.Player('player', {
height: '100%',
width: '100%',
playerVars: { controls: 0, // コントロールバーを表示しない
showinfo: 0, // 動画情報を表示しない
rel: 0, //0 に設定すると、再生した動画と同じチャンネルから関連動画が選択
playsinline: 1, //全画面表示 0はtrue、1はfalse
modestbranding: 1,//1=ロゴ非表示
iv_load_policy: 3,//動画アノテーション非表示
fs: 0,//全画面表示ボタン非表示
},
videoId: v_id,
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
//①
if(player.h.getAttribute('src')) {
player.h.setAttribute('data-src',player.h.getAttribute('src'));
player.h.setAttribute('src',"");
}
}
var $winWidth = $(window).width();
$(window).resize(function(){
var $winWidthResize = $(window).width();
if($winWidth !== $winWidthResize){
getVideoId();
if(be_v_id !== v_id){
player.loadVideoById(v_id);
}
}
});
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
<span style="color: #ff0000;">event.target.mute();
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) {
/* var names = {
'-1' : '未開始',
'0' : '終了',
'1' : '再生中',
'2' : '停止',
'3' : 'バッファリング中',
'5' : '頭出し済み'
};*/
if (event.data == 0) {
event.target.playVideo();
//$('.top_video_area').removeClass('opacity_str');
event.target.seekTo(0);
}else if(event.data == 1 || event.data == 2) {
$('.top_video_area').removeClass('opacity_str');
$('.top_video_area').addClass('opacity_str');
}else{
//$('.top_video_area').addClass('opacity_end');
$('.top_video_area').removeClass('opacity_str');
}
}
function stopVideo() {
player.stopVideo();
}
//②
function youtube_str() {
var $iframes = $(".top_video_area").find("iframe").attr('class', 'youtube');
if($iframes[0].getAttribute('data-src')) {
$iframes[0].setAttribute('src',$iframes[0].getAttribute('data-src'));
$iframes[0].removeAttribute('data-src');
}
}
$(window).on('load',function(){setTimeout(youtube_str(),3000);});基本的なソースに一部を足しています。
何をしているかというと画面サイズが切り替わったら幅を判定して、現在の動画IDと比較して違ったら動画IDを変えて読み込みなおすという作業です。
リサイズのたびにチェックしてしまいますが致し方ありません。
また、リサイズのたびに読み込んでしまうと負荷がかかるのでブレークポイントをまたいだ時だけ処理をします。
各読み方の設定も入れています。
今回は自動再生でループをする設定にしています。(無音設定です)
尚、srcを書き換える処理を入れていますが必要ないケースもあります。
複数のyoutubeに対応していませんので複数掲載する場合は①と②を消すか他の対処を入れてください。



コメント