实现网页元素的平滑滚动效果有多种方法,以下是几种常见的实现方式:
// 只需要添加这行CSS即可
document.documentElement.style.scrollBehavior = 'smooth';
// 然后使用常规的滚动方法
element.scrollIntoView();
window.scrollTo({ top: 0, behavior: 'smooth' });
function smoothScrollTo(element, duration = 500) {
const targetPosition = element.getBoundingClientRect().top;
const startPosition = window.pageYOffset;
const distance = targetPosition;
let startTime = null;
function animation(currentTime) {
if (startTime === null) startTime = currentTime;
const timeElapsed = currentTime - startTime;
const run = easeInOutQuad(timeElapsed, startPosition, distance, duration);
window.scrollTo(0, run);
if (timeElapsed < duration) requestAnimationFrame(animation);
}
// 缓动函数 - 二次缓入缓出
function easeInOutQuad(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);
}
// 使用示例
const button = document.querySelector('#scrollButton');
const target = document.querySelector('#targetElement');
button.addEventListener('click', () => {
smoothScrollTo(target);
});
// 滚动到特定元素
document.getElementById('section').scrollIntoView({
behavior: 'smooth'
});
// 或者滚动到特定位置
window.scrollTo({
top: 1000,
left: 0,
behavior: 'smooth'
});
$('html, body').animate({
scrollTop: $('#target').offset().top
}, 800);
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.scrollIntoView({
behavior: 'smooth'
});
}
});
}, {
threshold: 0.5
});
// 观察所有需要平滑滚动的元素
document.querySelectorAll('.scroll-target').forEach(el => {
observer.observe(el);
});
scroll-behavior: smooth
属性选择哪种方法取决于你的项目需求、目标浏览器支持范围和所需的自定义程度。