简体   繁体   中英

Automatically scroll to bottom of div

On my webpage the sql results are returned in a div where the maximum width and height has been defined and the overflow has been set to scroll. When someone visits the page I would like the default scroll position to be at the bottom. I have done a lot of research and the best solution I could find without using jQuery fails to work ( Scroll to bottom of div? ). Therefore I am wondering if anybody can explain where my error is or an alternate solution without using jQuery.

My Code

<html>
<style>
#test{
max-height: 150px;
max-width: 200px;
overflow: scroll;
background: #50a8ff;    
}
</style>    
<head>
<script language="javascript" type="text/javascript">
 var objDiv = document.getElementById("test");
objDiv.scrollTop = objDiv.scrollHeight;
</script>    
</head>
<body>
<div id="test"><h4>BIG TEXT</h4><h4>BIG TEXT</h4><h4>BIG TEXT</h4><h4>BIG TEXT</h4>
<h4>BIG TEXT</h4><h4>BIG TEXT</h4><h4>BIG TEXT</h4></div>    
</body>
</html>

This is a simplified version of my code to demonstrate the problem.

Potential Causes

As the SQL data is fetched once the page has loaded, therefore would the scroll height be set before the div is filled, would setting a delay solve this problem? Although in this simple example I have the same problem even though the data is not being loaded from an SQL database.

the scrollHeight method is not always correct sometimes it gives unexpected values
try this

1.add a div inside your overflow div

 <div class="container which has overflow">
   <div class="inner div with no padding"> // note that this div must not have any padding margins are fine
       MY CONTENT
   </div>
 </div>

2.JS code with jquery(I dont know about non-jquery)

 var div = $(".container"); // the div which has the overflow
 var div_inner = $(".container_inner"); //the div inside the overflow one
 var a = div_inner.outerHeight();//get the height of the inner div
 div.scrollTop(a);  // make the overflow fiv scroll to the bottom

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