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

以下の続き。

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

> * [CSS: 自動拡縮で background image を Window の width, height にフィットさせる | deadwood](https://www.d-wood.com/blog/2014/06/25_6407.html)

元記事はこちら。

> * [Perfect Full Page Background Image | CSS-Tricks](http://css-tricks.com/perfect-full-page-background-image/)
> * [背景画像をブラウザの枠いっぱいに表示するテクニックの考察 | コリス](http://coliss.com/articles/build-websites/operation/work/css-tutorial-perfect-full-page-background-image.html)

HTMLで画像を用意します。

“`html:full-page-bg.html

“`

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

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

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

“`javascript: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"); }); ``` ウィンドウサイズと画像サイズの取得方法が分かったので、画像の中心が表示されるよう、はみ出した分をずらす処理も加えました。 [/markdown]