javascript - 确保元素保持指定的纵横比

标签 javascript css scaling aspect-ratio

有没有办法在 CSS 中指定宽高比,例如 4:3 或 16:9,然后让 div(容器) block 适合当前窗口的宽度和高度?

enter image description here

很简单的问题,希望它有一个相对简单的答案。

编辑:那些仍然对仅使用样式实现此目的的一个很好的例子感兴趣的人将是 Bootstrap 的 responsive helpers类。

最佳答案

为此,我担心您需要一些 JS。我在这里使用了 jQuery:

function preserveAspect() {
  var scaled = $("#scaled");
  scaled.height("100%");
  scaled.width("100%");
  scaled.css("box-sizing", "border-box");
  var ratio = 16/9;
  var w = scaled.outerWidth();
  var h = scaled.outerHeight();

  if (w > ratio*h) {
    scaled.width(ratio*h);
    // horizontal centering is done using margin:auto in CSS
  } else if (h > w/ratio) {
    var newHeight = w/ratio;
    scaled.height(newHeight);
    // for vertical centering:
    scaled.css({marginTop: ($("body").height()-newHeight)/2});
  }

}
$(document).ready(function() {
    preserveAspect();
    $(window).resize(preserveAspect);
});

解释:

  1. 首先,我们将 div 的宽度和高度放大到 100%,以便我们知道它有多少空间。
  2. 然后我们往上看是不是太宽了说明宽度比较大 比高度倍数。
    • 如果是这样,改变宽度。高度已经达到 100%。
    • 否则它可能太高,在这种情况下我们希望比例为宽度除以比例。为了垂直居中,我们使用 margin-top 设置为 (window_height - element_height)/2。
  3. 如果这两个规则都不适用,则 div 已正确缩放。
  4. 最后,我们在文档完全加载时以及窗口大小发生变化时添加事件监听器。

完整代码和工作示例在这里: http://jsbin.com/efaRuXE/5/

关于javascript - 确保元素保持指定的纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21034420/

相关文章:

javascript - Bootstrap 悬停图像显示示例

css - 文本跟随 div

c# - 缩小一组高分辨率坐标?

javascript - 如何验证是否已调用 mockjax

javascript - 捕捉 ASP.NET 的 Response.Redirect

javascript - 如何在 HTML5 上索引具有相同 ID 的 div 标签

javascript - 在 cookie 中保存下拉选择

HTML div 宽度适合图像

wpf 调整窗口大小以使用所有监视器

python - PIL如何根据图像大小缩放文本大小