Scroll to bottom of div?

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

    This is much easier if you're using jQuery scrollTop:

    $("#mydiv").scrollTop($("#mydiv")[0].scrollHeight);
    
    0 讨论(0)
  • 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<br>"); // this is jquery!
    
    // doScroll is true, if we the bottom line is already visible
    if( doScroll) objDiv.scrollTop = objDiv.scrollHeight;
    
    0 讨论(0)
  • 2020-11-21 12:14

    You can use the Element.scrollTo() method.

    It can be animated using the built-in browser/OS animation, so it's super smooth.

    function scrollToBottom() {
        const scrollContainer = document.getElementById('container');
        scrollContainer.scrollTo({
            top: scrollContainer.scrollHeight,
            left: 0,
            behavior: 'smooth'
        });
    }
    
    // initialize dummy content
    const scrollContainer = document.getElementById('container');
    const numCards = 100;
    let contentInnerHtml = '';
    for (let i=0; i<numCards; i++) {
      contentInnerHtml += `<div class="card mb-2"><div class="card-body">Card ${i + 1}</div></div>`;
    }
    scrollContainer.innerHTML = contentInnerHtml;
    .overflow-y-scroll {
      overflow-y: scroll;
    }
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
    
    <div class="d-flex flex-column vh-100">
      <div id="container" class="overflow-y-scroll flex-grow-1"></div>
      <div>
        <button class="btn btn-primary" onclick="scrollToBottom()">Scroll to bottom</button>
      </div>
    </div>

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

    If this is being done for scrolling to the bottom of chat window, do the following

    The idea of scrolling to a particular div in the chat was the following

    1) Each chat div consisting of Person, time and message is run in a for loop with class chatContentbox

    2) querySelectorAll finds all such arrays. It could be 400 nodes (400 chats)

    3) go to the last one

    4) scrollIntoView()

    let lastChatBox = document.querySelectorAll('.chatContentBox'); 
    lastChatBox = lastChatBox[lastChatBox.length-1]; 
    lastChatBox.scrollIntoView(); 
    
    0 讨论(0)
  • 2020-11-21 12:15

    I use the difference between the Y coordinate of the first item div and the Y coordinate of the selected item div. Here is the JavaScript/JQuery code and the html:

    function scrollTo(event){
            // In my proof of concept, I had a few <button>s with value 
            // attributes containing strings with id selector expressions
            // like "#item1".
            let selectItem = $($(event.target).attr('value'));
            let selectedDivTop = selectItem.offset().top;
    
            let scrollingDiv = selectItem.parent();
    
            let firstItem = scrollingDiv.children('div').first();
            let firstItemTop = firstItem.offset().top;
    
            let newScrollValue = selectedDivTop - firstItemTop;
            scrollingDiv.scrollTop(newScrollValue);
        }
    <div id="scrolling" style="height: 2rem; overflow-y: scroll">
      <div id="item1">One</div>
      <div id="item2">Two</div>
      <div id="item3">Three</div>
      <div id="item4">Four</div>
      <div id="item5">Five</div>
    </div>

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

    Set the distance from the top of the scrollable element to be the total height of the element.

    const element = this.shadowRoot.getElementById('my-scrollable-div')
    element.scrollTop = element.scrollHeight
    
    0 讨论(0)
提交回复
热议问题