Javascript实现DIV滚动自动滚动到底部的代码
作者:
一个比较特殊的客户要求,在一个页面用表格显示数据,数据量不是很多,不希望使用浏览器的滚动条,只能在Div中滚动table中的数据,但是有个特殊的要求,就是必须将滚动条自动滚动到底部
查询了一下相关的资料,Div没有自动滚动的属性,只能模拟鼠标的滚动来现实想要的效果。
关键的部分部分在这里:div.scrollTop = div.scrollHeight;
下面是具体实现的精简代码:
<html>
<body>
<div id="divDetail" style="overFlow-y:scroll; width:250px;height: 200px;">
<table style="border:1px solid; ">
<tr><td>id</td><td>name</td><td>age</td><td>memo</td></tr>
<tr><td>000001</td><td>name1</td><td>24</td><td>memomemomemomemomemo</td></tr>
<tr><td>000002</td><td>name2</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000003</td><td>name3</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000004</td><td>name4</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000005</td><td>name5</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000002</td><td>name2</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000003</td><td>name3</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000004</td><td>name4</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000005</td><td>name5</td><td>23</td><td>memomemomemomemomemo</td></tr>
</table>
</div>
</body>
<script type="text/javascript" defer>
var div = document.getElementById('divDetail');
div.scrollTop = div.scrollHeight;
//alert(div.scrollTop);
</script>
</html>
其实,实现是很简单的但是一般很少有这种需求,期间还是走了一些弯路。
关键的部分部分在这里:div.scrollTop = div.scrollHeight;
下面是具体实现的精简代码:
复制代码 代码如下:
<html>
<body>
<div id="divDetail" style="overFlow-y:scroll; width:250px;height: 200px;">
<table style="border:1px solid; ">
<tr><td>id</td><td>name</td><td>age</td><td>memo</td></tr>
<tr><td>000001</td><td>name1</td><td>24</td><td>memomemomemomemomemo</td></tr>
<tr><td>000002</td><td>name2</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000003</td><td>name3</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000004</td><td>name4</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000005</td><td>name5</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000002</td><td>name2</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000003</td><td>name3</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000004</td><td>name4</td><td>23</td><td>memomemomemomemomemo</td></tr>
<tr><td>000005</td><td>name5</td><td>23</td><td>memomemomemomemomemo</td></tr>
</table>
</div>
</body>
<script type="text/javascript" defer>
var div = document.getElementById('divDetail');
div.scrollTop = div.scrollHeight;
//alert(div.scrollTop);
</script>
</html>
其实,实现是很简单的但是一般很少有这种需求,期间还是走了一些弯路。