【发布时间】:2016-09-27 23:21:44
【问题描述】:
我编写了一个小函数,它按比例减小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');
}
}
【问题讨论】:
-
你能接受这个浏览器支持吗? caniuse.com/#search=vw
-
@lipp 如果可能,我想保留 IE8
标签: javascript jquery