首页 前端知识 JS 界面滚动到顶部的多种方法,复制即用(卷王成长日记)。

JS 界面滚动到顶部的多种方法,复制即用(卷王成长日记)。

2025-03-16 12:03:36 前端知识 前端哥 325 9 我要收藏

方式一:window.requestAnimationFrame 平滑滚动到顶部

window.requestAnimationFrame 是一个用于在浏览器中实现平滑动画的 JavaScript 方法。它允许你在下一个浏览器重绘周期时执行一个指定的回调函数,从而优化动画性能,避免了使用 setTimeout 或 setInterval 时可能遇到的性能问题
(IE9以下不支持)

function scrollToTop(){
    const curPosition = document.documentElement.scrollTop || document.body.scrollTop;
    if (curPosition > 0) {
        window.requestAnimationFrame(scrollToTop); // 调用自己
        window.scrollTo(0, curPosition - curPosition / 10);
    }
}
html { //  使用CSS来添加一些过渡效果会让滚动更加平滑,并增强用户体验。可以添加以下CSS代码:
  scroll-behavior: smooth;
}

方式二:document 直接回到顶部

document.documentElement.scrollTop = document.body.scrollTop = 0;

方式三:window.scrollTo 把内容滚动到指定的坐标

// 支持平滑回到顶部 + 直接回到顶部
// window.scrollTo(100,500)方法可把内容滚动到指定的坐标;
//(IE9以下不支持)

 window.scrollTo({
     top:0,
     left:0,
     behavior:"smooth" // auto、smooth、instant
 })

方法四: setInterval 平滑滚动到顶部【建议使用】

平滑效果虽没有前面方法好,但 平滑兼容性最好

scrollToTop(){
	let timer = setInterval(()=>{
	    var top = document.body.scrollTop || document.documentElement.scrollTop;
	    var speed = top / 4;
	    if (document.body.scrollTop!=0) {
	        document.body.scrollTop -= speed;
	    }else {
	        document.documentElement.scrollTop -= speed;
	    }
	    if (top == 0)clearInterval(timer);
	}, 20);
}

扩展: scrollIntoView

例如在vue中弹窗,每次打开滚动到弹窗顶部。

this.$nextTick(()=>{
	let topview = document.querySelector("#topview"); // 获取锚点
	topview.scrollIntoView({block:"start"}); // 其他参数可控制滚动方式。
})
转载请注明出处或者链接地址:https://www.qianduange.cn//article/23819.html
标签
评论
发布的文章
大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!