jquery - 将高度设置为视口(viewport)宽度除以数字

标签 jquery html css

我有一个 DIV,我试图根据视口(viewport)宽度除以数字来设置其高度。这是一个 fiddle http://jsfiddle.net/7rfpvtu6/1/ ...但是如果 HTML/body 设置为 Overflow-y:hidden,DIV 会导致其个人滚动区域离开屏幕,从而导致内容的最后几行不可见。

当HTML/Body设置为overflow-y:hidden并且我在DIV中滚动时,如何使#container中内容的最后一行可见?

<html>

<head>
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <style>
    #container { border: solid 1px red; padding: 5px; overflow-y: scroll; max-width: 45%; }
            #main { border: solid 1px blue; background-color: blue; padding: 5px; }
            #text { border: solid 1px green; padding: 5px; }
            body, html { 
            overflow-y: hidden;
            overflow-x: hidden;
            }
  </style>
</head>

<body>
  <script>
    $(function() {

      var viewportWidth = $(window).width();
      var viewportHeight = $(window).height();

      $("#container").height(viewportWidth / 1.1);
      $("#text").text("The width for the viewport is " + viewportWidth + "px. And the height is " + viewportHeight + ". And the width of the DIV is " + $("#container").width() + ". And the height of the DIV is " + $("#container").height());
    });
  </script>

  <div id="container">
    <div id="text"></div>
    Add more content here to get it to scroll. Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum Lorem ipsum. END LINE@@@@@@@@@@@
    <div id="main">
      <!-- Leave this blank -->
    </div>
  </div>
</body>

</html>

最佳答案

您可以获得视口(viewport)高度或计算尺寸的最小值:

Demo

$(function() {

var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
var containersize = Math.min(viewportHeight, viewportWidth/1.1)

$("#container").outerHeight(containersize);

$("#text").text("The width for the viewport is " + viewportWidth + "px. And the height is " + viewportHeight + ". And the width of the DIV is " + $("#container").width() + ". And the height of the DIV is " + $("#container").height());
});

这样它就永远不会消失。请注意,我重置了 body 上的边距。

关于jquery - 将高度设置为视口(viewport)宽度除以数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33375215/

相关文章:

javascript - 打开一个多打开的 Accordion 选项卡并滚动到该部分中的哈希位置(IE 在评估查询字符串之前滚动到哈希 anchor ?)

javascript - 使用 jQueryeach 函数来计算具有相同类的 div

javascript - 单选按钮单击事件未触发

html - Firefox 的错误 - 输入的禁用属性在刷新时不重置

javascript - 将鼠标悬停在 slideToggle(2 个 div)上

html - 创建带有箭头的响应式 CSS 按钮

javascript - 如何让 jQuery UI 自动完成功能忽略标点符号,但显示它?

HTML Bootstrap 表单 <a> 元素未显示为 btn-secondary

html - 什么是::before 或::after 表达式,为什么它会显示在浏览器开发人员工具中?

WordPress - 如何在除主页以外的所有页面上隐藏标题图片?