[英]Scale div proportionally to fit viewport
我写了一个小函数,按比例减小div
的大小,直到它的高度与视口相同。 这非常有效。 我有2个问题我想解决
该函数背后的目标是使container
div永远不会高于视口。 这需要通过设置container
的width
来控制,因为内容是响应的。 为了演示目的,我使用了宽度为100%的简单图像。 由于缺乏浏览器支持,我没有使用vh
或vw
。 我需要支持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');
}
}
考虑到浏览器支持,我认为这种方法没有问题。 从我的角度来看,这看起来很干净。
要在视口高度减小时修复容器高度调整问题,只需在调用函数时将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');
}
}
我会使用vw
vh
CSS单位将div缩放到视口。
https://css-tricks.com/viewport-sized-typography/
IE8不支持它,但你可以找到它的polyfills https://github.com/saabi/vminpoly
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.