【问题标题】:Why does my code work with height:100px, but not height:100%?为什么我的代码适用于 height:100px,而不适用于 height:100%?
【发布时间】:2016-01-31 20:24:48
【问题描述】:

以下是向下滚动时从 DB 获取更多内容的代码。它主要是JQuery。

我不明白为什么将高度更改为 100 像素时它会起作用,但当高度设置为 100% 或自动时它不起作用。

<div id="contentBox" style="overflow: scroll;width: 200px; height: 100px;">
  <div id="actualContent">
    <p>
      <span>2</span>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero. 
    </p>
    <p>
      <span>3</span>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ornare facilisis mollis. Etiam non sem massa, a gravida nunc. Mauris lectus augue, posuere at viverra sed, dignissim sed libero.
    </p>
  </div>
</div>

$("#contentBox").scroll(function(){
  if($("#contentBox").scrollTop() >= ($("#actualContent").height() - $("#contentBox").height())){
       alert("Hi");
     }
 });

这里是链接:https://jsfiddle.net/8qv2ch9u/

如何让它在没有高度100px但内容填满浏览器大小的情况下工作?

【问题讨论】:

  • 因为如果高度为 100% 或自动,那么根据定义,它至少与其内容一样高。将 html, body { height:100% } 添加到您的 CSS。
  • 如何让它在没有高度100px但内容填满浏览器大小的情况下工作?

标签: javascript jquery css html


【解决方案1】:

使用height: 100px,元素确切地知道它需要做什么。

使用height: 100%,元素需要知道:百分比?

对于百分比高度,您需要提供一个参考框架。这是通过指定父级的高度来完成的。如果#contentBox 的父母也是一个百分比,那么祖父母也需要一个明确的高度。

基本上,如果您要使用百分比高度,则需要指定所有父元素的高度,包括根元素:

html, body { height: 100%; }

https://jsfiddle.net/8qv2ch9u/3/

这是规范中的相关部分:

W3C height property definition:

百分比
指定百分比高度。百分比是根据生成框的高度计算的 包含块。如果包含块的高度不是 明确指定并且此元素不是绝对定位的,该值计算为“自动”。

auto
高度取决于其他属性的值。

另见:

【讨论】:

  • 您提供的 jsfiddle 是错误的答案。我希望内容在完整的浏览器上。它的高度仍然为 100px,当我为 ContentBox 删除 100px 时,它不起作用。
  • 啊,你在我准备答案的时候修改了你的问题。我也修改了我的答案。干杯!
  • 您希望对溢出容器的内容进行什么处理?或者容器只是应该根据需要扩展?
  • 我希望它在您登录后就像 Quora 主页一样。我希望显示溢出的内容。
  • 为什么不直接删除所有height 规则,让高度始终基于内容大小? jsfiddle.net/8qv2ch9u/4
【解决方案2】:

正如 michael 所指出的,您可以设置body 高度,point 是以百分比设置元素的高度,它必须有一个父元素,它将从中获取百分比高度。或者在另一个div(父元素)中尝试整个代码并为父元素设置高度(以像素为单位),然后可以将子元素的高度设置为父元素的百分比。检查这个简单的 sn-p。

.parent{width:50px;height:600px;}
.childone{width:100%;height:80%;background-color:red;}
.childtwo{width:100%;height:19%;background-color:green;}
<div class='parent'>
<div class='childone'>I have 80% height of my parent</div>
  <div class='childtwo'>i have 19% height of my parent</div>
</div>

【讨论】:

    【解决方案3】:

    只需将100px 更改为100vh 以获得视图高度,或将vw 更改为视图宽度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-10
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      • 2017-03-31
      • 1970-01-01
      相关资源
      最近更新 更多