
jQueryプラグイン「Colorbox」でYoutube動画をモーダルで表示してみる(レスポンシブ対応済)
- 投稿日:2021/10/30
- JavaScript/jQuery
- colorbox, モーダル, youtube
「Colorbox」は簡単で多機能なモーダルウィンドウを表示できるjQueryプラグインです。
Colorboxの基本的な使い方(画像をモーダルで表示する方法)はこちらの記事で解説しましたが、今回はYoutubeをモーダルで表示する使い方を紹介します。
プレビュー
実際に動いているデモを下記から確認できます。
コードサンプル
1 2 3 4 5 6 | < p >< a class = "trig-youtube" href = "#youtube" >モーダルを開きます</ a ></ p > < div style = "display: none;" > < div id = "youtube" class = "youtube" > < iframe width = "560" height = "315" src = "https://www.youtube.com/embed/jhhGWsO0KKM" title = "YouTube video player" frameborder = "0" allow = "accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></ iframe > </ div > </ div > |
1 2 3 4 5 6 7 8 9 10 11 12 | .youtube{ position : relative ; width : 100% ; padding-top : 56.25% ; } .youtube iframe { position : absolute ; top : 0 ; right : 0 ; width : 100% !important ; height : 100% !important ; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $( function () { $(document).ready(colorbox); $(window).on( 'resize' ,colorbox); function colorbox() { var baseWidth = $( window ).width(); var w = baseWidth*0.8; var h = w*0.5625; $( '.trig-youtube' ).colorbox({ inline: true , opacity: 0.6, innerWidth: w, innerHeight: h, maxWidth: '90%' , maxHeight: '90%' }); }; }); |
Youtubeのiframe
はdiv.youtube
で内包してCSSでレスポンシブ化しています。
JSでcolorboxのinnerWidth
とinnerHeight
を設定することでiframe
のサイズを指定していますが、innerWidth
とinnerHeight
の数値を自動的に計算するように調整しています。