繁体   English   中英

使用“background-size:contains”调整背景图像的高度

[英]Getting the height of a background image resized using “background-size: contain”

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

为了确保每个图像都使用最大可用宽度,我给它以下背景大小:

background-size: 100% auto;

但是,某些图像比可用的屏幕高度高。

为了确保图像完全可见(至少使用滚动条),我需要给body元素指定调整大小的背景图像的高度。

但是,似乎没有办法在JavaScript中掌握调整大小的背景图像的高度。

这是真的? 毕竟我是否必须诉诸普通的图像元素?

有很多方法可以获得静态背景图像的大小,比如如何在jQuery中获取背景图像大小? 但他们显然不适用于此。

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

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

html, body { height:100%; }
body {
    background-image: url('http://placehold.it/50x100');
    background-repeat: no-repeat;
    background-size: 100% auto;
}

静态图像的尺寸为50x100 ,其尺寸适合占据主体元素的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();

纯JS方法将是最快的,正如这个jsPerf示例所示

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

<!-- 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM