实现平滑滚动有多种方法,下面我将介绍几种常用的技术方案:
html {
scroll-behavior: smooth;
}
优点: - 最简单实现方式 - 纯CSS解决方案,无需JavaScript - 浏览器原生支持,性能良好
缺点: - 无法自定义滚动行为 - 兼容性问题(IE不支持)
window.scrollTo({
top: 1000, // 滚动到的位置
behavior: 'smooth' // 平滑滚动
});
document.getElementById('target-element').scrollIntoView({
behavior: 'smooth'
});
function smoothScrollTo(targetPosition, duration = 1000) {
const startPosition = window.pageYOffset;
const distance = targetPosition - startPosition;
let startTime = null;
function animation(currentTime) {
if (startTime === null) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const run = ease(timeElapsed, startPosition, distance, duration);
window.scrollTo(0, run);
if (timeElapsed < duration) requestAnimationFrame(animation);
}
// 缓动函数
function ease(t, b, c, d) {
t /= d / 2;
if (t < 1) return c / 2 * t * t + b;
t--;
return -c / 2 * (t * (t - 2) - 1) + b;
}
requestAnimationFrame(animation);
}
// 使用示例
smoothScrollTo(1000); // 滚动到距离顶部1000px的位置
$('html, body').animate({
scrollTop: $('#target-element').offset().top
}, 1000); // 1000毫秒的动画时间
一些流行的平滑滚动库: - smooth-scroll - locomotive-scroll - fullPage.js
scroll-behavior
或原生JavaScript方法requestAnimationFrame
而不是setTimeout
您可以根据项目需求和浏览器兼容性要求选择最适合的方法。