繁体   English   中英

按比例缩放div以适合视口

[英]Scale div proportionally to fit viewport

我写了一个小函数,按比例减小div的大小,直到它的高度与视口相同。 这非常有效。 我有2个问题我想解决

  1. 这样做有更干净的方法吗?
  2. 一旦视口的高度减小,当视口增加时,它不会缩放。

该函数背后的目标是使container div永远不会高于视口。 这需要通过设置containerwidth来控制,因为内容是响应的。 为了演示目的,我使用了宽度为100%的简单图像。 由于缺乏浏览器支持,我没有使用vhvw 我需要支持IE8。

演示Jsfiddle

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');
  }

}

的jsfiddle

我会使用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.

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