Auto-scroll to the bottom of a div

后端 未结 3 626
长发绾君心
长发绾君心 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
    })();
    

提交回复
热议问题