<分区>
标签 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/