使用"background-size: contain"调整大小后,获取背景图片的高度

4

我有一个图片库。每张图片都是一张background-image,可以横跨整个页面。

为了确保每张图片使用最大可用宽度,我设置了以下背景大小:

background-size: 100% auto;

然而,一些图片比可用的屏幕高度还要高。 为了确保图片完整可见(至少使用滚动条),我需要给body元素设置经过调整大小的背景图像的高度。 然而,在JavaScript中似乎没有办法获得调整大小后的背景图片的高度。 这是真的吗?我还需要使用普通的图像元素吗? 有很多方法可以获取静态背景图像的大小,例如如何在jQuery中获取背景图像大小?,但它们显然不适用于此处。
2个回答

15

关键是使用静态图像的尺寸,计算出图像的长宽比,然后使用实际元素的尺寸来确定调整大小后的图像的计算尺寸。

例如,假设您有以下内容:

html, body { height:100%; }
body {
    background-image: url('http://placehold.it/50x100');
    background-repeat: no-repeat;
    background-size: 100% auto;
}
静态图像的尺寸为 50x100,并且大小调整为占据 body 元素宽度的 100%。因此,body 元素的宽度将等于调整后的图像宽度。如果您想计算调整后的图像高度,只需使用图像的纵横比。在本例中,图像的调整后高度将为 800px,因为 (400*100)/50 = 800

在此处查看示例

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();

纯JS方法:此处示例

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();

根据这个 jsPerf 实例的演示,纯JS方法将是最快的。


没错,这个很好用。这里有一个 jFiddle(使用 jQuery 获取 body 的宽度因为懒惰):http://jsfiddle.net/NpDbX/ - Pekka
1
哦,伟大的思想总是相似的:我们确实在同一分钟内找到了解决方案 :) 你的更好,而且能够监听resize(),很酷。谢谢。 - Pekka
真的吗?那就试着在background-image中放置一个相对路径,例如/path/to image,而不是http://...。 - Aymane Shuichi
这正是我的问题,而且解决方案很好用。 - Aymane Shuichi
我不得不将 style.height = x 移到 setTimeout(function() { #在这里设置 } 中。希望这能帮助到某些人。 - Joe Eifert

1
这对我有用(在滑块内部):

<!-- CSS -->
    <style>
        div.img { 
            background-repeat: no-repeat;
            background-position: center center;
            -webkit-background-size: cover;
            -moz-background-size: cover;
            -o-background-size: cover;
            background-size: cover;
        }
        div.img:nth-of-type(1) {background-image: url('img.jpg');}
        div.img:nth-of-type(2) {background-image: url('img.jpg'); 
        }
    </style>

    <!-- HTML -->
    <div class-"img"></div>
    <div class-"img"></div>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接