JS让页面滚动到顶部和底部

滚动到顶部,Class名为go-top的点击事件:

jQuery('.go-top').on('click', function (e) {
    e.preventDefault();
    jQuery('html, body').animate({ scrollTop: 0 }, duration);
    return false;
})

滚动到底部,Class名为go-bottom的点击事件:

jQuery('.go-bottom').on('click', function (e) {
    var t = document.body.clientHeight;
    window.scroll({ top: t, left: 0, behavior: 'smooth' });
})

我们发现上们滚动到底部代码虽简单,但没有滚动动画,于是我们优化一下

jQuery('.go-bottom').on('click', function (e) {
    (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);
        }
    })();
})

(DeepSeek编写)不使用jQuery的JS函数scrollToTop()

/**
 * 回到页面顶部
 * @param {Object} options 配置选项
 * @param {number} options.duration 动画持续时间(毫秒),默认500
 * @param {string} options.easing 缓动函数,可选:'linear', 'ease', 'ease-in', 'ease-out', 'ease-in-out'
 * @param {Function} options.onComplete 完成回调
 */
function scrollToTop(options = {}) {
  const {
    duration = 500,
    easing = 'ease-in-out',
    onComplete = null
  } = options;
  
  const start = window.pageYOffset;
  const startTime = performance.now();
  
  // 缓动函数映射
  const easingFunctions = {
    'linear': t => t,
    'ease': t => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t,
    'ease-in': t => t * t,
    'ease-out': t => t * (2 - t),
    'ease-in-out': t => t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
  };
  
  const ease = easingFunctions[easing] || easingFunctions['ease-in-out'];
  
  function animate(currentTime) {
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    const easedProgress = ease(progress);
    
    window.scrollTo(0, start * (1 - easedProgress));
    
    if (progress < 1) {
      requestAnimationFrame(animate);
    } else if (onComplete && typeof onComplete === 'function') {
      onComplete();
    }
  }
  
  // 如果已经在顶部,直接调用完成回调
  if (start === 0) {
    if (onComplete) onComplete();
    return;
  }
  
  requestAnimationFrame(animate);
}

使用实例

scrollToTop({
  duration: 800,
  easing: 'ease-out'
});

参考资料:

SegmentFault 思否 – js实现滚动条滑动到底部

本文采用 CC BY-NC-SA 3.0 Unported 许可,转载请以超链接注明出处。
原文地址:JS让页面滚动到顶部和底部 作者:松鼠小
上一篇
下一篇