缓动滑动到底部
使用requestAnimationFrame缓动滑动到底部
setTimeout(scrollToBottom, 100);scrollToBottom = () => {console.log('scrollToBottom');(function smoothscroll() {const currentScroll = document.documentElement.scrollTop || document.body.scrollTop; // 已经被卷掉的高度const clientHeight = document.documentElement.clientHeight; // 浏览器高度const scrollHeight = document.documentElement.scrollHeight; // 总高度if (scrollHeight - 10 > currentScroll + clientHeight) {window.requestAnimationFrame(smoothscroll);window.scrollTo(0, currentScroll + (scrollHeight - currentScroll - clientHeight) / 2);}})();};
指定dom的滚动条滑动到底部
一般情况下使用body的滚动条,但是特殊情况下需要指定某个dom的滚动条滑动到最底部,因此需要指定滚动条容器,方便计算出容器的高度和容器内容的总高度;
setTimeout(scrollToBottom, 100);scrollToBottom() {const domWrapper = document.querySelector('.wrapper'); // 外层容器 出现滚动条的dom(function smoothscroll() {const currentScroll = domWrapper.scrollTop; // 已经被卷掉的高度const clientHeight = domWrapper.offsetHeight; // 容器高度const scrollHeight = domWrapper.scrollHeight; // 内容总高度if (scrollHeight - 10 > currentScroll + clientHeight) {window.requestAnimationFrame(smoothscroll);domWrapper.scrollTo(0, currentScroll + (scrollHeight - currentScroll - clientHeight) / 2);}})();}
