【问题标题】:jQuery alert when scroll position equals divs content height [duplicate]滚动位置等于div内容高度时的jQuery警报[重复]
【发布时间】:2017-09-03 01:23:22
【问题描述】:

我希望当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

【问题讨论】:

  • 如果我理解正确,如果滚动位置在内容的末尾,您想触发某些功能?
  • 是的,最终结果将触发滚动动画到下一部分
  • 您需要在您的代码中添加一个scroll 事件处理程序,您的当前只会在页面加载后执行:example
  • 好的,谢谢。这让我后来省了很多麻烦

标签: javascript jquery html css


【解决方案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

【讨论】:

  • 如果我要求您在每段代码的旁边发表评论来解释它到底在说什么,会不会太过分了?我是 jQuery 的新手。谢谢
  • 没问题,伙计!
  • 非常感谢。最后一个问题,container[0] 后面的括号有什么作用?
  • container 是一个 jQuery 对象(数组的修改实例)。当我们在[0] 处取消索引时,我们最终会得到原始的 html 元素。然后我们可以访问它的scrollHeight。另一种写法可能是container.prop('scrollHeight')
猜你喜欢
  • 2012-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 2014-12-31
  • 1970-01-01
相关资源
最近更新 更多