基础概念: Chrome 平滑滚动是指在 Google Chrome 浏览器中,页面内容能够以流畅、连续的方式滚动,而不是传统的跳跃式滚动。这种效果通常通过 CSS 属性和 JavaScript 实现,为用户提供更舒适的浏览体验。
相关优势:
类型:
scroll-behavior
属性实现。应用场景:
可能遇到的问题及原因:
requestAnimationFrame
控制动画帧率。scroll-behavior
属性。示例代码(CSS 平滑滚动):
html {
scroll-behavior: smooth;
}
示例代码(JavaScript 平滑滚动):
function smoothScroll(target, duration) {
const targetElement = document.querySelector(target);
const targetPosition = targetElement.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 = 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);
}
// 使用示例
document.querySelector('#scrollButton').addEventListener('click', () => {
smoothScroll('#targetSection', 1000);
});
以上代码展示了如何在 Chrome 中实现平滑滚动的效果,包括 CSS 和 JavaScript 的实现方式。
领取专属 10元无门槛券
手把手带您无忧上云