滚动DIV元素的特定滚动条

时间:2013-10-30 13:00:04

标签: javascript jquery

我有一个带滚动条的div元素,我只想在顶部或底部的某个事件上滚动此滚动条

<div id="scroll_box" style="height:300px; overflow:auto;">
 <pre>
  Top
  .
  .
  .
  .
  .
  .
  .
  .
  .
  .
  Bottom
 </pre>
</div>
<button id="go_top">Top</button>
<button id="go_bottom">Bottom</button>

我不希望主滚动条(窗口)移动

我试过了

$('#scroll_box').animate({scrollTop: $("#scroll_box").offset().top},"fast");
$('#scroll_box').animate({scrollBottom: $("#scroll_box").offset().bottom},"fast");

我是初学者,我先在这里搜索,然后猜测代码

1 个答案:

答案 0 :(得分:4)

您使用的scrollTop值不正确,scrollBottom不存在。此外,您需要将这些语句附加到每个按钮的click事件,否则它们都会在加载时运行并相互取消。试试这个:

$('#go_top').click(function() {
    $('#scroll_box').animate({scrollTop: 0 },"fast");
});
$('#go_bottom').click(function() {
    $('#scroll_box').animate({scrollTop: $("#scroll_box pre").height() },"fast");
});

Example fiddle