以下のコードは正常に機能しますが、より合理化できると確信しています。
スクリプトは基本的に画像のサイズを変更し、画面サイズに関係なく、画像を含むdivの中央に水平に配置します。
関数"resizeBg"内の2つの関数は、異なるクラス(".bg1"と".bg2")の画像を含む異なるdiv(".block1"と".block2")を指すという事実を除けば、同じです。
関数resizeBGを各divに個別に適用する必要があります。一方の画像は縦向きで、もう一方の画像は横向きである可能性があるため、結果は画像の比率によって異なります。これが私が今これを機能させることができる唯一の方法ですが、私はそれがとても単純でよりきれいであるかもしれないことを理解しています。
HTML
<div class="block block1">
IMAGE
</div>
<div class="block block2">
IMAGE
</div>
CSS
.block1 {background: #000000;}
.block2 {background: ffffff;}
.block {
float: left;
width: 50%;
height: 100%;
overflow: hidden;
}
.bgwidth {
width: 100%;
}
.bgheight {
height: 100%;
}
jQuery
jQuery(window).load(function() {
// FULLSCREEN BACKGROUND IMAGE
var theWindow = $(window);
var block1 = $('.block1');
bg1 = block1.children(".bg1");
var block2 = $('.block2');
bg2 = block2.children(".bg2");
aspectRatio1 = bg1.width() / bg1.height();
aspectRatio2 = bg2.width() / bg2.height();
function resizeBg() {
$('.block1').each(function() {
if ((block1.width() / block1.height()) < aspectRatio1) {
bg1.removeClass('bgwidth').addClass('bgheight');
if(bg1.width() > block1.width()) {
bg1.each(function(){
//get width (unitless) and divide by 2
var hWide = ($(this).width() - block1.width())/2;
// attach negative and pixel for CSS rule
hWide = '-' + hWide + 'px';
$(this).addClass("js-fix").css({
"margin-left" : hWide
});
});
}
else {
bg1.each(function(){
$(this).removeClass("js-fix").css({
"margin-left" : 0 + 'px'
});
});
};
} else {
bg1.removeClass('bgheight').addClass('bgwidth');
bg1.each(function(){
$(this).removeClass("js-fix").css({
"margin-left" : 0 + 'px'
});
});
}
});
$('.block2').each(function() {
if ((block2.width() / block2.height()) < aspectRatio2) {
bg2.removeClass('bgwidth').addClass('bgheight');
if(bg2.width() > block2.width()) {
bg2.each(function(){
//get width (unitless) and divide by 2
var hWide = ($(this).width() - block2.width())/2;
// attach negative and pixel for CSS rule
hWide = '-' + hWide + 'px';
$(this).addClass("js-fix").css({
"margin-left" : hWide
});
});
}
else {
bg2.each(function(){
$(this).removeClass("js-fix").css({
"margin-left" : 0 + 'px'
});
});
};
} else {
bg2.removeClass('bgheight').addClass('bgwidth');
bg2.each(function(){
$(this).removeClass("js-fix").css({
"margin-left" : 0 + 'px'
});
});
}
});
}
theWindow.resize(function () {
resizeBg();
}).trigger("resize");
});