我的页面上有一个div:

<div id='div1' style='overflow:scroll;overflow-x:hidden;max-height:200px;'></div>

我怎样才能使div滚动到div的底部??不是页面,只是DIV。


当前回答

我在这里看到的所有答案,包括目前“被接受”的答案,实际上都是错误的,因为他们设置了:

scrollTop = scrollHeight

而正确的方法是设置:

scrollTop = scrollHeight - clientHeight

换句话说:

$('#div1').scrollTop($('#div1')[0].scrollHeight - $('#div1')[0].clientHeight);

或动画:

$("#div1").animate({
  scrollTop: $('#div1')[0].scrollHeight - $('#div1')[0].clientHeight
}, 1000);

其他回答

我在一个遗留代码库中工作,试图迁移到Vue。

在我的特定情况下(在引导模式中包装的可滚动div), v-if显示了新内容,我希望页面向下滚动到这些内容。为了让这种行为工作,我必须等待vue完成重新渲染,然后使用jQuery滚动到模态的底部。

所以…

this.$nextTick(function() {
    $('#thing')[0].scrollTop = $('#thing')[0].scrollHeight;
})

滚动窗口到目标div的底部。

function scrollToBottom(id){
  div_height = $("#"+id).height();
  div_offset = $("#"+id).offset().top;
  window_height = $(window).height();
  $('html,body').animate({
    scrollTop: div_offset-window_height+div_height
  },'slow');
}

scrollToBottom('call_div_id');

你可以使用下面的代码滚动到底部的div页面加载。

$(document).ready(function(){
  $('div').scrollTop($('div').scrollHeight);
});
$(document).ready(function() {
    let width = $(window).width();
    let element = $("#YourId");
    let positionFromTop = element.offset().top + element.prop("scrollHeight");
    $("html, body").animate({
        scrollTop: Math.abs($(window).height() - positionFromTop)
    }, 500);
});

更新:请参阅Mike Todd的解决方案以获得完整的答案。


$("#div1").animate({ scrollTop: $('#div1').height()}, 1000);

如果你想让它变成动画(超过1000毫秒)。

$('#div1').scrollTop($('#div1').height())

如果你想要即时的。