滚动位置等于div内容高度时的jQuery警报

时间:2017-04-07 15:25:54

标签: javascript jquery html css

我希望当div 的滚动位置等于 div内的内容高度时,会显示提醒消息。我写了一些jQuery,并相信我非常接近能够做到这一点。

然而,缺少某些东西。忽略稍后将使用的滚动条div。感谢

$(document).ready(function() {

  var box1_height = $("#box1").height();
  var scroll_pos = $("#box1").scrollTop();

  if (box1_height == scroll_pos) {
    alert("It's working");
  }
});
* {
  margin: 0;
  padding: 0;
}

body {
  overflow: hidden;
}

#background_1 {
  background-image: url("http://placehold.it/350x150");
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  position: relative;
}

.scroller {
  width: 100%;
  height: 100vh;
  overflow: scroll;
}

.content {
  width: 80%;
  height: 80vh;
  margin: 10vh auto;
  background-color: rgba(0, 0, 0, 0.6);
  overflow: scroll;
  box-size: border-box;
}
<div id="background_1">
  <div class="scroller">
    <div id="box1" class="content">
      content is here
    </div>
  </div>
</div>

这是CodePen Link

1 个答案:

答案 0 :(得分:1)

您需要执行以下操作来检测此信息:

var container = $("#box1")                      //Fetch the container element once, so we don't squander performance on re-fetches
var box1_height = container.height();           //Get the visible height of the container (not the actual height with scroll)
var scroll_height = container[0].scrollHeight;  //Get the content height of the container
var scroll_pos = container.scrollTop();         //Get the top location of the scrollbar in that container
if(scroll_height == box1_height + scroll_pos){  //Check if we're exactly at the bottom
    alert("It's working");
}

说明:

这是因为您知道滚动条的最高值,但要检测您是否位于容器的底部,您实际上需要知道滚动条的底部值。这是通过以下方式实现的:

scroll_height == box1_height + scroll_pos