![](/img/trans.png)
[英]How to determine when user scrolls to bottom of container div? For Infinite Scroll
[英]Always scroll the div container to the bottom when creating child divs
首先这些是我的参考
我创建了一些div并将它们放入div容器中。 我希望容器总是向下滚动到底部的最新div。
$(document).ready(function() { var container = $("#container"); var i = 0; $("#btn").click(function() { i++; var div = $("<div></div>"); div.addClass("d"); div.html("Container " + i); container.append(div); container.scrollTop(container.height()); }); });
body { background: white; } #container { height: 160px; width: 120px; overflow-y: scroll; background: gray; } .d { height: 30px; margin-bottom: 10px; background: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn">-- Add --</button> <div id="container"> </div>
正如你所看到的,这很好用,直到我创建超过8个div。 然后逻辑将中断,容器不再滚动。
容器应滚动到当前div,编号为i(当前索引)
仅仅因为高度总是固定的 ,而是考虑使用所有子元素的高度滚动, 包括它们的上/下边距 。 换句话说,如果没有指定固定高度,则容器的高度。
更准确地说,您只需要滚动所有子元素的高度减去容器的固定高度,这是溢出的部分 。 这就是你的代码部分工作的原因,因为直到8个元素的溢出低于容器的固定高度( 8 * 40 = 320
=> 320 - 160(fixed height) = 160(overflow)
)
$(document).ready(function() { var container = $("#container"); var i = 0; $("#btn").click(function() { i++; var div = $("<div></div>"); div.addClass("d"); div.html("Container " + i); container.append(div); container.scrollTop(container.find('.d').length * ($('.d').height() + 10) - container.height()); }); });
body { background: white; } #container { height: 160px; width: 120px; overflow-y: scroll; background: gray; } .d { height: 30px; margin-bottom: 10px; background: red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn">-- Add --</button> <div id="container"> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.