Auto-scroll to the bottom of a div

后端 未结 3 637
长发绾君心
长发绾君心 2021-01-25 18:05

I have a div with overflow set to scroll which essentially streams data line by line off a file. I\'d like to scroll automatically to the bottom of the div whenever the stream o

相关标签:
3条回答
  • 2021-01-25 18:44

    There's no way to automatically scroll an element to the bottom. Use element.scrollTop = element.scrollHeight.

    If you don't know when the element is going to resize, you could add a poller:

    (function(){
        var element = document.getElementById("myElement");
        var lastHeight = element.scrollHeight;
        function detectChange(){
            var currentHeight = element.scrollHeight;
            if(lastHeight != currentHeight){
                element.scrollTop = currentHeight;
                lastHeight = currentHeight;
            }
        }
        detectChange();
        setInterval(detectChange, 200); //Checks each 200ms = 5 times a second
    })();
    
    0 讨论(0)
  • 2021-01-25 18:45

    Some old code of mine with a running example that will stay at the bottom when new content is added, if the user scrolls it will not more it to the bottom.

    var chatscroll = new Object();
    chatscroll.Pane = 
        function(scrollContainerId)
        {
            this.bottomThreshold = 25;
            this.scrollContainerId = scrollContainerId;
        }
    
    chatscroll.Pane.prototype.activeScroll = 
        function()
        {
            var scrollDiv = document.getElementById(this.scrollContainerId);
            var currentHeight = 0;
    
            if (scrollDiv.scrollHeight > 0)
                currentHeight = scrollDiv.scrollHeight;
            else 
                if (objDiv.offsetHeight > 0)
                    currentHeight = scrollDiv.offsetHeight;
    
            if (currentHeight - scrollDiv.scrollTop - ((scrollDiv.style.pixelHeight) ? scrollDiv.style.pixelHeight : scrollDiv.offsetHeight) < this.bottomThreshold)
                scrollDiv.scrollTop = currentHeight;
    
            scrollDiv = null;
        }
    
    0 讨论(0)
  • 2021-01-25 18:47

    A lot of the scrollHeight implementations didn't work for me, offsetHeight seemed to do the trick.

    Pretty sure that scrollHeight tries to move it to the bottom of the height of the static element, not the height of the scrollable area.

    var pane = document.getElementById('pane');
    pane.scrollTop = pane.offsetHeight;
    
    0 讨论(0)
提交回复
热议问题