Scroll to bottom of div?

前端 未结 30 2720
日久生厌
日久生厌 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:06

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

    $('#scroll').scrollTop(1000000);
    
    0 讨论(0)
  • 2020-11-21 12:06

    Java Script:

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

    Scrolls to the last line of the content present.

    0 讨论(0)
  • 2020-11-21 12:06

    You can use the HTML DOM scrollIntoView Method like this:

    var element = document.getElementById("scroll");
    element.scrollIntoView();
    
    0 讨论(0)
  • 2020-11-21 12:06

    On my Angular 6 application I just did this:

    postMessage() {
      // post functions here
      let history = document.getElementById('history')
      let interval    
      interval = setInterval(function() {
        history.scrollTop = history.scrollHeight
        clearInterval(interval)
      }, 1)
    }
    

    The clearInterval(interval) function will stop the timer to allow manual scroll top / bottom.

    0 讨论(0)
  • 2020-11-21 12:07

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

    $('html, body').animate({scrollTop:$(document).height()}, 1000);
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题