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

标签 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 .

最佳答案

您需要执行以下操作来检测此问题:

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

关于javascript - 滚动位置等于 div 内容高度时的 jQuery 警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43281842/

上一篇:html - 制作适合视频纵横比的框,加上静态大小的页脚

下一篇:css - 我有水平显示的州和城市列表,但显示不均匀

相关文章:

javascript - 如何在 JavaScript 中处理 'define'

javascript - 传递值将 Ajax 抛出到一个 php 文件

javascript 模块模式变量范围

php - 刷新数据库并删除条目

javascript - .focus() 和 onfocus ="this.value = this.value"刷新后不会将光标移动到输入的末尾

javascript - d3js SVG :title tooltip doesn't show up

javascript - 为 href 属性获取相同的值

javascript - jQuery 更改回调上下文

javascript - jQuery Mobile 选项卡导航延迟

html - POCO HTMLForm 如何读取名称为 invoice[items][1] 的输入表单元素