Scroll to bottom of div?

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

    You can also, using jQuery, attach an animation to html,body of the document via:

    $("html,body").animate({scrollTop:$("#div-id")[0].offsetTop}, 1000);

    which will result in a smooth scroll to the top of the div with id "div-id".

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

    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.

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

    use :

    var element= $('element');
    var maxScrollTop = element[0].scrollHeight - element.outerHeight();
    element.scrollTop(maxScrollTop);
    

    or check scroll to bottom :

        var element = $(element);
        var maxScrollTop = element[0].scrollHeight - element.outerHeight();
        element.on('scroll', function() {
            if ( element.scrollTop() >= maxScrollTop ) {
                alert('scroll to bottom');
            }
        });
    
    0 讨论(0)
  • 2020-11-21 12:25

    using jQuery animate:

    $('#DebugContainer').stop().animate({
      scrollTop: $('#DebugContainer')[0].scrollHeight
    }, 800);
    
    0 讨论(0)
  • 2020-11-21 12:25

    Scroll to the last element inside the div:

    myDiv.scrollTop = myDiv.lastChild.offsetTop
    
    0 讨论(0)
  • 2020-11-21 12:26

    My Scenario: I had an list of string, in which I had to append a string given by a user and scroll to the end of the list automatically. I had fixed height of the display of the list, after which it should overflow.

    I tried @Jeremy Ruten's answer, it worked, but it was scrolling to the (n-1)th element. If anybody is facing this type of issue, you can use setTimeOut() method workaround. You need to modify the code to below:

    setTimeout(() => {
        var objDiv = document.getElementById('div_id');
        objDiv.scrollTop = objDiv.scrollHeight
    }, 0)
    

    Here is the StcakBlitz link I have created which shows the problem and its solution : https://stackblitz.com/edit/angular-ivy-x9esw8

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