简体   繁体   English

自动滚动到div的底部

[英]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. 在我的网页上,sql结果以div返回,该div中已定义了最大宽度和高度,并且溢出已设置为滚动。 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? ). 我已经做了大量的研究,没有使用jQuery我找不到的最佳解决方案无法正常工作( 滚动到div的底部? )。 Therefore I am wondering if anybody can explain where my error is or an alternate solution without using jQuery. 因此,我想知道是否有人可以在不使用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? 由于在加载页面后就获取了SQL数据,因此是否会在div填充之前设置滚动高度,设置延迟会解决此问题吗? Although in this simple example I have the same problem even though the data is not being loaded from an SQL database. 尽管在此简单示例中,即使没有从SQL数据库加载数据,我也遇到了同样的问题。

the scrollHeight method is not always correct sometimes it gives unexpected values scrollHeight方法并不总是正确的,有时会给出意外的值
try this 尝试这个

1.add a div inside your overflow div 1.在您的溢出div中添加一个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) 2.带有jquery的JS代码(我不了解非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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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