The key is to use the static image's dimensions, calculate the aspect ratio of the image, and then use the actual element's dimensions to figure out the computed dimensions of the resized image.
For instance, lets assume you had the following:
html, body { height:100%; }
body {
background-image: url('http://placehold.it/50x100');
background-repeat: no-repeat;
background-size: 100% auto;
}
The static image's dimensions are 50x100
, and it is sized to take up a width of 100%
of the body element. Therefore the body
element's width would be equal to the resized image's width. If you wanted to calculate the resized height of the image, you would just use the image's aspect ratio. In this case, the image's resized height would be 800px
, because (400*100)/50 = 800
EXAMPLE HERE
var img = new Image();
img.src = $('body').css('background-image').replace(/url(|)$/ig, "");
$(window).on("resize", function () {
$('body').height($('body').width() * img.height / img.width);
}).resize();
Pure JS approach: EXAMPLE HERE
var img = new Image();
img.src = window.getComputedStyle(document.body).getPropertyValue("background-image").replace(/url(|)$/ig, "");
function resize(){
var bgHeight = document.body.offsetWidth * img.height / img.width;
document.body.style.height = bgHeight + 'px';
}
window.onresize = resize; resize();
The pure JS method is going to be the fastest, as demonstrated by this jsPerf example.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…