js实现滚动条
监听滚动事件
通过 window.addEventListener('scroll', callback) 监听页面滚动事件。回调函数中可获取当前滚动位置 window.scrollY(垂直方向)或 window.scrollX(水平方向)。
window.addEventListener('scroll', () => {
console.log('当前垂直滚动位置:', window.scrollY);
});
平滑滚动到指定位置
使用 window.scrollTo() 方法实现滚动,通过 behavior: 'smooth' 启用平滑动画效果。

// 滚动到页面顶部
window.scrollTo({
top: 0,
behavior: 'smooth'
});
// 滚动到特定元素
document.getElementById('target').scrollIntoView({
behavior: 'smooth'
});
自定义滚动条样式
通过 CSS 修改滚动条外观,适用于 WebKit 内核浏览器(Chrome、Edge、Safari)。
/* 垂直滚动条 */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
禁止页面滚动
通过 document.body.style.overflow = 'hidden' 临时禁止页面滚动,常用于弹窗出现时。

// 禁止滚动
document.body.style.overflow = 'hidden';
// 恢复滚动
document.body.style.overflow = '';
获取元素滚动位置
使用 element.scrollTop 或 element.scrollLeft 获取容器内滚动位置,适用于 div 等可滚动元素。
const div = document.querySelector('.scrollable-div');
console.log('垂直滚动位置:', div.scrollTop);
滚动事件节流优化
高频滚动事件可能影响性能,通过 setTimeout 或 requestAnimationFrame 节流处理。
let ticking = false;
window.addEventListener('scroll', () => {
if (!ticking) {
requestAnimationFrame(() => {
// 执行实际逻辑
ticking = false;
});
ticking = true;
}
});






