<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>【ネイティブ化】JavaScriptでbackground: coverみたいなことをする方法</title>
<style type="text/css">
html, body {
height: 100%;
}
body {
margin: 0;
}
#coverParent {
width: 100%;
height: 100%;
overflow: hidden;
position: absolute;
top: 0;
left: 0;
z-index: -1;
}
#cover {
position: absolute;
}
</style>
</head>
<body>
<div id="coverParent"><img src="image01.jpg" width="1920" height="1280" alt="" id="cover"></div>
<script>
(function(){
// 使用する変数を宣言
var win_w, win_h, win_ratio, cover_w, cover_h, cover_ratio, style;
// 参照する要素をキャッシュ
var cover = document.getElementById('cover');
// 画像の縦の比率を求める
cover_w = cover.getAttribute('width');
cover_h = cover.getAttribute('height');
cover_ratio = cover_w / cover_h;
// ウィンドウのリサイズイベントに合わせて計算する
var fit = function(){
// ウィンドウサイズを取得
win_w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
win_h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
// ウィンドウの縦の比率を求める
win_ratio = win_w / win_h;
// 画像の比率がウィンドウより大きければ、画像の高さを100%にする
if(cover_ratio > win_ratio){
style = [
'width: auto',
'height: 100%',
'margin-top: 0',
'margin-left: ' + (-(win_h * cover_ratio) / 2) + 'px',
'top: 0',
'left: 50%'
];
// そうじゃない場合は、画像の幅を100%にする
}else{
style = [
'width: 100%',
'height: auto',
'margin-left: 0',
'margin-top: ' + (-(win_w / cover_ratio) / 2) + 'px',
'top: 50%',
'left: 0'
];
}
cover.style.cssText = style.join(';');
}
if(window.addEventListener){
window.addEventListener('resize', fit, false);
// ~ IE8
} else if(window.attachEvent){
window.attachEvent('onresize', fit);
}
fit();
}());
</script>
</body>
</html>