滚动 DIV 元素的特定滚动条

scrolling a particular scrollbar of DIV element

本文关键字:滚动条 DIV 元素 滚动      更新时间:2023-09-26

我有一个带有滚动条的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");

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

您对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");
});

示例小提琴