简体   繁体   中英

Auto-scroll to the bottom of a div

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 overflows, but without using a "Click here to scroll to bottom" button.

I already know of the scrollTop = scrollHeight solution , but that requires some kind of event trigger on the client's side. I don't want this element to be interactive; it should scroll by itself.

Is there any way to achieve this?

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
})();

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;
    }

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM