简体   繁体   English

自动滚动到div的底部

[英]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. 我有一个带溢出设置滚动的div,它基本上逐行地从文件中流出数据。 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. 我想在流溢出时自动滚动到div的底部,但不使用“单击此处滚动到底部”按钮。

I already know of the scrollTop = scrollHeight solution , but that requires some kind of event trigger on the client's side. 我已经知道了scrollTop = scrollHeight解决方案 ,但是在客户端需要某种事件触发器。 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 . 使用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. 很多scrollHeight实现对我来说都不起作用,offsetHeight似乎可以解决这个问题。

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. 很确定scrollHeight尝试将其移动到静态元素高度的底部,而不是可滚动区域的高度。

var pane = document.getElementById('pane');
pane.scrollTop = pane.offsetHeight;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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