[jQuery] jQuery をつかって背景画像をフルスクリーンで表示させる

以下の続き。

.htc でうまくいかなかったので、jQuery で対応してみます。

元記事はこちら。

HTMLで画像を用意します。

full-page-bg.html
<img src="/img/bg.png" id="full-page-bg" alt="">

css で表示用のクラスを設定。

full-page-bg.scss
#full-page-bg { position: fixed; top: 0; left: 0; }
.bgwidth { width: 100%; }
.bgheight { height: 100%; }

ウィンドウサイズと画像サイズの縦横比率を比較して、JavaScript で width もしくは height のどちらかを 100% 表示させています。

full-page-bg.js
$(window).load(function() {
  'use strict';
  var theWindow = $(window),
  $bg = $("#full-page-bg"),
  aspectRatio = $bg.width() / $bg.height();
  function resizeBg() {
    if ( (theWindow.width() / theWindow.height()) < aspectRatio ) {
      $bg.removeClass().addClass('bgheight');
      // 横にはみ出した幅を計算して左へずらす
      var positionLeft = Math.round(
        ($bg.width() - theWindow.width()) / 2) * -1;
      $bg.css({left:positionLeft});
      // console.log('positionLeft: ' + positionLeft);
    } else {
      $bg.removeClass().addClass('bgwidth');
      // 縦にはみ出した幅を計算して上へずらす
      var positionTop = Math.round(
        ($bg.height() - theWindow.height()) / 2) * -1;
      $bg.css({top:positionTop});
      // console.log('positionTop: ' + positionTop);
    }
  }
  theWindow.resize(resizeBg).trigger("resize");
});

ウィンドウサイズと画像サイズの取得方法が分かったので、画像の中心が表示されるよう、はみ出した分をずらす処理も加えました。