简体   繁体   English

创建子div时,始终将div容器滚动到底部

[英]Always scroll the div container to the bottom when creating child divs

first these are my references 首先这些是我的参考

jQuery Scroll to bottom of page/iframe jQuery滚动到页面底部/ iframe

jQuery Scroll To bottom of the page jQuery Scroll到页面底部

I create some divs and put them into a div container. 我创建了一些div并将它们放入div容器中。 I want the container always scrolling down to the newest div at the bottom. 我希望容器总是向下滚动到底部的最新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> 

As you can see, this works fine untill I create more than 8 divs. 正如你所看到的,这很好用,直到我创建超过8个div。 Then the logic will break and the container does not scroll anymore. 然后逻辑将中断,容器不再滚动。

The container should scroll to the current div with the number i (the current index) 容器应滚动到当前div,编号为i(当前索引)

Simply because the height is always fixed , instead consider scrolling with the height of all the child elements including their top/bottom margin . 仅仅因为高度总是固定的 ,而是考虑使用所有子元素的高度滚动, 包括它们的上/下边距 In other words, the height of the container if there is no fixed height specified. 换句话说,如果没有指定固定高度,则容器的高度。

To be more precise you only need to scroll with the height of all the child element minus the fixed height of the container which is the overflowing part . 更准确地说,您只需要滚动所有子元素的高度减去容器的固定高度,这是溢出的部分 That's why your code work partially because until 8 elements you have an overflow lower than the fixed height of the container ( 8 * 40 = 320 => 320 - 160(fixed height) = 160(overflow) ) 这就是你的代码部分工作的原因,因为直到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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM