jQuery 提供的
scrollTop() 方法,可以用来返回或设置匹配元素的滚动条的垂直位置。通过这个方法,配合获取到的
scrollHeight。我们可以将一个元素的滚动条移动到最底部。或者将整个页面滚动到最底部。
1,效果图
点击“移动到最底部”按钮后,上方的div就会将滚动条移动到最下面。
<html>
<head>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn1").click(function(){
var scrollHeight = $('#div1').prop("scrollHeight");
$('#div1').scrollTop(scrollHeight,200);
});
});
</script>
</head>
<body>
<div id="div1" style="border:1px solid black;width:200px;height:200px;overflow:auto">
第1行<br>第2行<br>第3行<br>第4行<br>第5行<br>
第6行<br>第7行<br>第8行<br>第9行<br>第10行<br>
第11行<br>第12行<br>第13行<br>第14行<br>第15行<br>
第16行<br>第17行<br>第18行<br>第19行<br>第20行
</div>
<button id="btn1">移动到最底部</button>
</body>
</html>
原文出自:www.hangge.com 转载请保留原文链接:http://www.hangge.com/blog/cache/detail_1360.html
3,添加过渡动画
上面样例点击按钮后,滚动条位置直接改变,会显得很生硬。我们可以使用 animate() 方法给其添加个滚动过渡的动画效果。
将按钮点击的相关代码改成如下。点击后,上面的 div 会逐渐滚动,直至移动到最底部(整个过程 400 毫秒)
$("#btn1").click(function(){
var scrollHeight = $('#div1').prop("scrollHeight");
$('#div1').animate({scrollTop:scrollHeight}, 400);
});