js 实现置顶
使用 position: sticky 实现置顶
通过 CSS 的 position: sticky 属性可以轻松实现元素在滚动到特定位置时置顶。这种方法不需要 JavaScript,但可以通过 JavaScript 动态添加或移除该类。
.sticky {
position: sticky;
top: 0;
z-index: 100;
}
通过 JavaScript 动态添加 sticky 类:
const element = document.querySelector('.header');
element.classList.add('sticky');
监听滚动事件动态置顶
通过监听 scroll 事件,判断滚动位置并动态切换元素的 position 属性实现置顶效果。
const header = document.querySelector('.header');
const stickyOffset = header.offsetTop;
window.addEventListener('scroll', () => {
if (window.pageYOffset > stickyOffset) {
header.style.position = 'fixed';
header.style.top = '0';
header.style.width = '100%';
} else {
header.style.position = 'static';
}
});
使用 Intersection Observer API
现代浏览器支持的 IntersectionObserver 可以更高效地监听元素是否进入视口,实现置顶效果。
const observer = new IntersectionObserver(
(entries) => {
entries.forEach(entry => {
const header = entry.target;
if (entry.intersectionRatio < 1) {
header.classList.add('sticky');
} else {
header.classList.remove('sticky');
}
});
},
{ threshold: [1] }
);
const header = document.querySelector('.header');
observer.observe(header);
平滑滚动到顶部
实现点击按钮平滑滚动到页面顶部的功能:
const scrollToTop = () => {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
};
document.querySelector('.top-button').addEventListener('click', scrollToTop);
动态显示返回顶部按钮
在页面滚动一定距离后显示返回顶部按钮:
const topButton = document.querySelector('.top-button');
window.addEventListener('scroll', () => {
if (window.pageYOffset > 300) {
topButton.style.display = 'block';
} else {
topButton.style.display = 'none';
}
});
以上方法可以根据具体需求选择或组合使用。position: sticky 是最简单的实现方式,而滚动监听和 Intersection Observer 提供了更灵活的控制。平滑滚动和动态按钮增强了用户体验。







