开发者

Auto-scroll to the bottom of a div

开发者 https://www.devze.com 2023-04-11 14:18 出处:网络
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 overflo

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?


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;


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

精彩评论

暂无评论...
验证码 换一张
取 消