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:31

This is much easier if you're using jQuery:

$("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
查看更多
人气声优
3楼-- · 2018-12-31 03:32

Just as a bonus snippet. I'm using angular and was trying to scroll a message thread to the bottom when a user selected different conversations with users. In order to make sure that the scroll works after the new data had been loaded into the div with the ng-repeat for messages, just wrap the scroll snippet in a timeout.

$timeout(function(){
    var messageThread = document.getElementById('message-thread-div-id');
    messageThread.scrollTop = messageThread.scrollHeight;
},0)

That will make sure that the scroll event is fired after the data has been inserted into the DOM.

查看更多
孤独寂梦人
4楼-- · 2018-12-31 03:33

You can use the following code:

function scrollToBottom(id){
   var div = document.getElementById(id);
   div.scrollTop = div.scrollHeight - div.clientHeight;
}

To perform a smooth scroll, use the following code (require jQuery):

function scrollSmoothToBottom (id) {
   var div = document.getElementById(id);
   $('#' + id).animate({
      scrollTop: div.scrollHeight - div.clientHeight
   }, 500);
}

See the sample on JSFiddle

And that's how it works:

enter image description here

Ref: scrollTop, scrollHeight, clientHeight

查看更多
旧时光的记忆
5楼-- · 2018-12-31 03:33

Found this really helpful, thank you.

For the Angular 1.X folks out there:

angular.module('myApp').controller('myController', ['$scope', '$document',
  function($scope, $document) {

    var overflowScrollElement = $document[0].getElementById('your_overflow_scroll_div');
    overflowScrollElement[0].scrollTop = overflowScrollElement[0].scrollHeight;

  }
]);

Just because the wrapping in jQuery elements versus HTML DOM elements gets a little confusing with angular.

Also for a chat application, I found making this assignment after your chats were loaded to be useful, you also might need to slap on short timeout as well.

查看更多
美炸的是我
6楼-- · 2018-12-31 03:34

Java Script:

document.getElementById('messages').scrollIntoView(false);

Scrolls to the last line of the content present.

查看更多
还给你的自由
7楼-- · 2018-12-31 03:38

Here's what I use on my site:

var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
查看更多
登录 后发表回答