Scroll to bottom of div?

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

    small addendum: scrolls only, if last line is already visible. if scrolled a tiny bit, leaves the content where it is (attention: not tested with different font sizes. this may need some adjustments inside ">= comparison"):

    var objDiv = document.getElementById(id);
    var doScroll=objDiv.scrollTop>=(objDiv.scrollHeight-objDiv.clientHeight);                   
    
    // add new content to div
    $('#' + id ).append("new line at end
    "); // this is jquery! // doScroll is true, if we the bottom line is already visible if( doScroll) objDiv.scrollTop = objDiv.scrollHeight;

提交回复
热议问题