CSS 平滑滚动效果是指通过 CSS 动画实现页面内容的平滑过渡,通常用于滚动条的滚动行为,使得用户在浏览网页时能够获得更加流畅的视觉体验。
html {
scroll-behavior: smooth;
}
<a href="#section1" class="smooth-scroll">Go to Section 1</a>
<div id="section1">Section 1 Content</div>
.smooth-scroll {
color: blue;
text-decoration: none;
}
.smooth-scroll:hover {
text-decoration: underline;
}
document.querySelectorAll('.smooth-scroll').forEach(link => {
link.addEventListener('click', function (e) {
if (this.hash !== "") {
e.preventDefault();
const hash = this.hash;
window.scrollTo({
top: document.querySelector(hash).offsetTop,
behavior: 'smooth'
});
}
});
});
原因:不同浏览器对 CSS 平滑滚动属性的支持程度不同。
解决方法:
html {
scroll-behavior: smooth;
-webkit-scroll-behavior: smooth; /* Safari 和 Chrome */
}
原因:JavaScript 动画在某些情况下可能会导致页面卡顿,尤其是在低性能设备上。
解决方法:
requestAnimationFrame
来优化动画性能。function smoothScroll(element, to, duration) {
const start = window.pageYOffset;
const change = to - start;
let currentTime = 0;
const increment = 20;
function animateScroll() {
currentTime += increment;
const val = Math.easeInOutQuad(currentTime, start, change, duration);
window.scrollTo(0, val);
if (currentTime < duration) {
setTimeout(animateScroll, increment);
}
}
animateScroll();
}
Math.easeInOutQuad = function (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;
};
通过以上方法,你可以实现 CSS 平滑滚动效果,并解决可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云