Scroll to bottom of div?

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

    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
    Card ${i + 1}
    `; } scrollContainer.innerHTML = contentInnerHtml;
    .overflow-y-scroll {
      overflow-y: scroll;
    }
    
    
    

提交回复
热议问题