提问人:Pekka 提问时间:1/15/2014 最后编辑:CommunityPekka 更新时间:3/3/2016 访问量:12276
使用“background-size: contain”调整背景图像的高度
Getting the height of a background image resized using "background-size: contain"
问:
所以我有一个图片库。每个图像都是整个页面的延伸。background-image
为了确保每个图像都使用最大可用宽度,我给它以下背景大小:
background-size: 100% auto;
但是,某些图像高于可用的屏幕高度。
为了确保图像完全可见(至少使用滚动条),我需要为元素指定调整大小的背景图像的高度。body
但是,似乎无法在 JavaScript 中获取调整大小的背景图像的高度。
这是真的吗?毕竟,我必须求助于普通的图像元素吗?
有很多方法可以获取静态背景图像的大小,例如如何在jQuery中获取背景图像大小?但它们显然不适用于这里。
答:
15赞
Josh Crozier
1/15/2014
#1
关键是使用静态图像的尺寸,计算图像的纵横比,然后使用实际元素的尺寸来计算调整大小图像的计算尺寸。
例如,假设您有以下情况:
html, body { height:100%; }
body {
background-image: url('http://placehold.it/50x100');
background-repeat: no-repeat;
background-size: 100% auto;
}
静态图像的尺寸为 ,其大小为占用 body 元素的宽度。因此,元素的宽度将等于调整大小的图像的宽度。如果要计算图像的调整大小高度,则只需使用图像的纵横比即可。在这种情况下,图像调整大小的高度将为 ,因为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 示例所演示的那样。
评论
0赞
Pekka
1/15/2014
是的,这很好用。下面是一个 jFiddle(使用 jQuery 获取正文的宽度,因为懒惰): jsfiddle.net/NpDbX
1赞
Pekka
1/15/2014
哦,伟大的思想家的想法是一样的:我们在同一分钟内就找到了解决方案:)不过你的更好,并且听 resize(),很酷。谢谢。
0赞
Aymane Shuichi
12/4/2014
真?好吧,尝试在 background-image 中放置一个相对路径,例如 /path/to image,而不是 http:// ...
0赞
Aymane Shuichi
12/4/2014
这正是我的问题,解决方案 stackoverflow.com/a/25430236/2672358 工作正常
0赞
Joe Eifert
12/15/2017
我不得不把.希望这对某人有所帮助。style.height = x
setTimeout(function() { #set it here }
1赞
seanwbarker
3/3/2016
#2
这对我有用(在滑块内):
<!-- 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>
评论