Scroll to bottom of div?

2018-12-31 03:04发布

I am creating a chat using ajax requests in rails and I'm trying to get a div to scroll to the bottom without much luck.

I am wrapping everything in this div:

#scroll {
    height:400px;
    overflow:scroll;
}

Is there a way to keep it scrolled to the bottom by default using JS?

Is there a way to keep it scrolled to the bottom after an ajax request?

18条回答
梦该遗忘
2楼-- · 2018-12-31 03:47

This will let you scroll all the way down regards the document height

$('html, body').animate({scrollTop:$(document).height()}, 1000);
查看更多
临风纵饮
3楼-- · 2018-12-31 03:50

If you don't want to rely on scrollHeight, the following code helps:

$('#scroll').scrollTop(1000000);
查看更多
不再属于我。
4楼-- · 2018-12-31 03:51

using jQuery animate:

$('#DebugContainer').stop().animate({
  scrollTop: $('#DebugContainer')[0].scrollHeight
}, 800);
查看更多
浮光初槿花落
5楼-- · 2018-12-31 03:53

I know this is an old question, but none of these solutions worked out for me. I ended up using offset().top to get the desired results. Here's what I used to gently scroll the screen down to the last message in my chat application:

$("#html, body").stop().animate({
     scrollTop: $("#last-message").offset().top
}, 2000);

I hope this helps someone else.

查看更多
心情的温度
6楼-- · 2018-12-31 03:54

A very simple method to this is to set the scroll to to the height of the div.

var myDiv = document.getElementById("myDiv");
window.scrollTo(0, myDiv.innerHeight);
查看更多
永恒的永恒
7楼-- · 2018-12-31 03:55

Newer method :

this.scrollIntoView(false);
查看更多
登录 后发表回答