[英]Scale div proportionally to fit viewport
I have written a small function that proportionally reduces the size of a div
until it's height is the same as the viewport. 我写了一个小函数,按比例减小div
的大小,直到它的高度与视口相同。 This works perfectly. 这非常有效。 I have 2 issues I'd like to fix 我有2个问题我想解决
The objective behind the function is so that the container
div is never higher than the viewport. 该函数背后的目标是使container
div永远不会高于视口。 This needs to be controlled by setting the width
of the container
as it contents are responsive. 这需要通过设置container
的width
来控制,因为内容是响应的。 I've used a simple image with a width of 100% for demonstration purposes. 为了演示目的,我使用了宽度为100%的简单图像。 I haven't used vh
or vw
due to lack of browser support. 由于缺乏浏览器支持,我没有使用vh
或vw
。 I need to support IE8. 我需要支持IE8。
function setImageViewPointHeight() {
// get current viewport height
var targetHeight = $(window).height();
// get current container height
var containerHeight = $('.container').height();
// get current container width
var containerWidth = $('.container').width();
// only set width if container is higher than viewport
if (containerHeight > targetHeight) {
// keep reducing container height/width value by 0.1% until target is reached
while (containerHeight > targetHeight) {
containerHeight = containerHeight - (containerHeight * .01);
containerWidth = containerWidth - (containerWidth * .01);
}
// now we have desired calculated width
$('.container').width(containerWidth + 'px');
}
}
Taking into account browser support I don't see a problem with this approach. 考虑到浏览器支持,我认为这种方法没有问题。 It seems clean enough from my perspective. 从我的角度来看,这看起来很干净。
To fix your issue of container height adjustment when the viewport height is reduced simply set the width
to initial
when the function is invoked. 要在视口高度减小时修复容器高度调整问题,只需在调用函数时将width
设置为initial
值。
function setImageViewPointHeight() {
$('.container').css('width', 'initial'); <-- add this
var targetHeight = $(window).height();
var containerHeight = $('.container').height();
var containerWidth = $('.container').width();
if (containerHeight > targetHeight) {
while (containerHeight > targetHeight) {
containerHeight = containerHeight - (containerHeight * .01);
containerWidth = containerWidth - (containerWidth * .01);
}
$('.container').width(containerWidth + 'px');
}
}
I would use the vw
vh
CSS units to scale the div to the viewport. 我会使用vw
vh
CSS单位将div缩放到视口。
https://css-tricks.com/viewport-sized-typography/ https://css-tricks.com/viewport-sized-typography/
IE8 doesn't support it, but you can find polyfills for it https://github.com/saabi/vminpoly IE8不支持它,但你可以找到它的polyfills https://github.com/saabi/vminpoly
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.