LoginSignup
1
1

More than 5 years have passed since last update.

baserJSで埋め込んだYouTubeをレスポンシブに対応させる

Last updated at Posted at 2014-12-05

コーポレートサイトにちょうどいいJavaScriptライブラリ baserJS の解説記事です。

Webサイトと詳しいAPIリファレンスはこちら baserJS Webサイト

デモ

デモはこちは http://codepen.io/YusukeHirao/pen/dPGyMx


今回はちょっと裏ワザ的なやり方です。

YouTubeを埋め込む

HTMLは前々回と同様にdata-iddata-widthdata-heightを指定するだけです。

<div class="youtube" data-id="rb0zOstIiyU" data-width="1920" data-height="1080"></div>

ここでのdata-widthdata-heightは縦横比(アスペクト比)の基準の幅と高さになります。1920x1080であれば、16x9としても問題ありません。

コンテナの幅まで広げる

レスポンシブに対応 を銘打ってますが、ぶっちゃけ釣りみたいなもので、要するにただのフルード要素です。

コンテナの幅が 最大が1920pxでウィンドウの幅が1920px以下になると幅めいいっぱいになるとしましょう。

そしてコンテナの中にbcYoutubeメソッドを使って自動生成されるiframe要素のスタイルを調整します。

.youtube {
  overflow: hidden;
  width: 100%;
  max-width: 1920px;
}

.youtube iframe {
  width: 100%;
  height: auto;
}

しかしこの方法、通常では上手く行きません。

画像(img要素)はheight: autoにすると、幅を基準に画像の元の縦横比から自動的に高さが決まりますが、iframe要素は特に縦横比をキープするような仕様にはなっていません。

JS側でiframeの縦横比をキープさせる

$('.youtube')
    .bcYoutube()
    .find('iframe')
        .bcKeepAspectRatio();

YouTube化した要素の中からjQueryのfindメソッドでiframeを探して、そのままチェインでbcKeepAspectRatioメソッドを実行します。

ポイントは iframe要素に対してbcKeepAspectRatioを使う というところです。

1
1
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
1
1