Scroll to bottom of div?

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

    Like you, I'm building a chat app and want the most recent message to scroll into view. This ultimately worked well for me:

    //get the div that contains all the messages
    let div = document.getElementById('message-container');
    
    //make the last element (a message) to scroll into view, smoothly!
    div.lastElementChild.scrollIntoView({ behavior: 'smooth' });
    
    0 讨论(0)
  • 2020-11-21 12:18

    smooth scroll with Javascript:

    document.getElementById('messages').scrollIntoView({ behavior: 'smooth', block: 'end' });

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

    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);
    
    0 讨论(0)
  • 2020-11-21 12:19

    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.

    0 讨论(0)
  • 2020-11-21 12:21
    var mydiv = $("#scroll");
    mydiv.scrollTop(mydiv.prop("scrollHeight"));
    

    Works from jQuery 1.6

    https://api.jquery.com/scrollTop/

    http://api.jquery.com/prop/

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

    Sometimes the most simple is the best solution: I do not know if this will help, it helped me to scroll it were ever I wanted too. The higher the "y=" is,the more down it scrolls and of course "0" means top, so there for example "1000" could be bottom, or "2000" or "3000" and so on, depending how long your page is. This usually works in a button with onclick or onmouseover.

    window.scrollTo(x=0,y=150);
    
    0 讨论(0)
提交回复
热议问题