简体   繁体   中英

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 Scroll To bottom of the page

I create some divs and put them into a div container. I want the container always scrolling down to the newest div at the bottom.

 $(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. 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)

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) )

 $(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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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