Scroll to bottom of div?

前端 未结 30 2729
日久生厌
日久生厌 2020-11-21 11:56

I am creating a chat using Ajax requests and I\'m trying to get messages div to scroll to the bottom without much luck.

I am wrapping everything in this div:



        
30条回答
  •  日久生厌
    2020-11-21 12:08

    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 with JQuery:

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

    See the example on JSFiddle

    Here's why this works:

    Ref: scrollTop, scrollHeight, clientHeight

提交回复
热议问题