3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

YouTubeAPIで映像をモーダル表示

Last updated at Posted at 2016-02-12

デモ:http://jsrun.it/mo4_9/uz3k/

クリックしてモーダルウィンドウを表示。
オーバーレイをクリックすると閉じる、映像は一時停止。

<div id="ytplayer"></div>
<div id="modal_overlay"></div>
<div id="js-modal_btn">CLICK!</div>
<script>
/* ============================
 * youtube api
 * ============================ */

// API読み込み
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
        height: '315',
        width: '560',
        videoId: 'rAiw2SXPS-4',
        playerVars: {
            fs: 0 // 全画面表示させない
        },
        events: {
          'onReady': onPlayerReady
        }
    });
}
var modal_overlay = document.getElementById("modal_overlay");
function onPlayerReady(event) {
	modal_overlay.addEventListener("click", pauseVideo, false);
}
function pauseVideo() {
    player.pauseVideo();
}
</script>

映像は中央寄せfixed

#modal_overlay{
    display: none;
	position: fixed;
	width: 100%;
	height: 100%;
	background: rgba(0,0,0,.8); 
	z-index: 1; 
}

#js-modal_btn{
	width: 100px;
	height: 100px;
	background-color: red;
}

#ytplayer{
	display: none;
	position:fixed;
	top:50%;
	left:50%;
	-moz-transform:translate(-50%, -50%);
	-webkit-transform:translate(-50%, -50%);
	-o-transform:translate(-50%, -50%);
	-ms-transform:translate(-50%, -50%);
	transform:translate(-50%, -50%);
	z-index: 2;
}

モーダルの開閉

/* ============================
 * モーダル
 * ============================ */

var $modal_overlay = $('#modal_overlay'),
    $modal_btn = $('#js-modal_btn'),
    $ytplayer = $('#ytplayer');

// オープン
$modal_btn.on('click', function(){
    $modal_overlay.fadeIn();
    $ytplayer.fadeIn();
});
// クローズ
$modal_overlay.on('click', function(){
    $modal_overlay.fadeOut();  
    $ytplayer.fadeOut();  
});

// サイズ変更
$(window).on('load resize', function(){
    var $ww = $(window).innerWidth();
    if ($ww > 700) {
        $ytplayer.css('width', '560px').css('height', '315px');
    }else{
        $ytplayer.css('width', '100%').css('height', $ww*9/16);
    }
});

参考
YouTube 埋め込みプレーヤーとプレーヤーのパラメータ

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?