JS实现回到页面顶部的五种写法(从实现到增强)

   2025-02-05 9590
核心提示:使用window.scrollTo或document.documentElement.scrollTop方法实现:function scrollToTop() {window.scrollTo(0, 0);}使用wind

使用window.scrollTo或document.documentElement.scrollTop方法实现:

function scrollToTop() {  window.scrollTo(0, 0);}
使用window.scrollTo方法结合requestAnimationFrame实现平滑滚动效果:
function smoothScrollToTop() {  const currentScroll = document.documentElement.scrollTop || document.body.scrollTop;  if (currentScroll > 0) {    window.requestAnimationFrame(smoothScrollToTop);    window.scrollTo(0, currentScroll - (currentScroll / 8));  }}
使用scrollIntoView方法实现滚动到指定元素的顶部:
function scrollToElementTop(element) {  element.scrollIntoView({ behavior: 'smooth', block: 'start' });}
使用animate方法实现平滑滚动效果:
function animateScrollToTop(duration) {  const start = document.documentElement.scrollTop || document.body.scrollTop;  const target = 0;  const distance = target - start;  const startTime = performance.now();    function step() {    const currentTime = performance.now();    const elapsed = currentTime - startTime;    const progress = Math.min(elapsed / duration, 1);    const easing = function(t) { return t * (2 - t); }; // 缓动函数,例如使用二次方函数    const position = start + distance * easing(progress);        window.scrollTo(0, position);        if (progress < 1) {      window.requestAnimationFrame(step);    }  }    window.requestAnimationFrame(step);}
增强版本:添加按钮元素,并绑定点击事件:
<button id="scrollToTopBtn">回到顶部</button>
document.getElementById('scrollToTopBtn').addEventListener('click', scrollToTop);function scrollToTop() {  window.scrollTo({ top: 0, behavior: 'smooth' });}

以上是五种常见的回到页面顶部的实现方法,从最基本的滚动到顶部到增强版带有平滑滚动效果和按钮点击事件的写法。可以根据具体需求选择相应的方法来实现回到页面顶部的功能。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言