組件結構
<div class="scroll-container">
<div class="scroll-track">
<div class="scroll-thumb"></div>
</div>
<div class="scroll-content">
<!-- 長內容 -->
</div>
</div>
核心邏輯
- 計算內容高度
contentH、可視區高度 viewportH、軌道高度 trackH、滑塊高度 thumbH = trackH * (viewportH / contentH)。
- 滑塊拖拽、點擊軌道、點擊箭頭、滾輪、鍵盤方向鍵均同步更新
content.scrollTop 與 thumb.style.top。
- 比例關係:
scrollTop / (contentH - viewportH) = thumbTop / (trackH - thumbH)。
完整 ES6 類實現
class CustomScrollbar {
constructor(containerSelector) {
this.container = document.querySelector(containerSelector);
this.content = this.container.querySelector('.scroll-content');
this.track = this.container.querySelector('.scroll-track');
this.thumb = this.container.querySelector('.scroll-thumb');
this.thumbHeight = 0;
this.isDragging = false;
this.startY = 0;
this.init();
}
init() {
this.updateGeometry();
this.bindEvents();
window.addEventListener('resize', () => this.updateGeometry());
}
updateGeometry() {
const contentH = this.content.scrollHeight;
const viewportH = this.container.clientHeight;
if (contentH <= viewportH) {
this.track.style.display = 'none';
return;
}
this.track.style.display = 'block';
this.thumbHeight = Math.max(30, (viewportH / contentH) * this.track.clientHeight);
this.thumb.style.height = this.thumbHeight + 'px';
this.syncThumb();
}
bindEvents() {
// 拖拽滑塊
this.thumb.addEventListener('mousedown', e => this.onDragStart(e));
// 點擊軌道跳轉
this.track.addEventListener('click', e => this.onTrackClick(e));
// 滾輪
this.container.addEventListener('wheel', e => this.onWheel(e), { passive: false });
// 鍵盤
this.container.addEventListener('keydown', e => this.onKeyDown(e));
// 全局拖拽移動/結束
document.addEventListener('mousemove', e => this.onDragMove(e));
document.addEventListener('mouseup', () => this.onDragEnd());
}
onDragStart(e) {
this.isDragging = true;
this.startY = e.clientY - this.thumb.offsetTop;
e.preventDefault();
}
onDragMove(e) {
if (!this.isDragging) return;
let top = e.clientY - this.startY;
top = Math.max(0, Math.min(top, this.track.clientHeight - this.thumbHeight));
this.thumb.style.top = top + 'px';
this.syncContent(top);
}
onDragEnd() { this.isDragging = false; }
onTrackClick(e) {
if (e.target === this.thumb) return;
const trackRect = this.track.getBoundingClientRect();
const clickY = e.clientY - trackRect.top;
let top = clickY - this.thumbHeight / 2;
top = Math.max(0, Math.min(top, this.track.clientHeight - this.thumbHeight));
this.animateThumb(top);
}
onWheel(e) {
e.preventDefault();
const delta = e.deltaY > 0 ? 40 : -40;
this.scrollBy(delta);
}
onKeyDown(e) {
const step = 40;
if (e.key === 'ArrowDown') this.scrollBy(step);
else if (e.key === 'ArrowUp') this.scrollBy(-step);
else if (e.key === 'PageDown') this.scrollBy(this.container.clientHeight);
else if (e.key === 'PageUp') this.scrollBy(-this.container.clientHeight);
else if (e.key === 'Home') this.scrollTo(0);
else if (e.key === 'End') this.scrollTo(this.content.scrollHeight - this.container.clientHeight);
}
scrollBy(delta) {
const newTop = this.content.scrollTop + delta;
this.scrollTo(newTop);
}
scrollTo(top) {
top = Math.max(0, Math.min(top, this.content.scrollHeight - this.container.clientHeight));
this.content.scrollTop = top;
this.syncThumb();
}
syncThumb() {
const ratio = this.content.scrollTop / (this.content.scrollHeight - this.container.clientHeight);
const thumbTop = ratio * (this.track.clientHeight - this.thumbHeight);
this.thumb.style.top = thumbTop + 'px';
}
syncContent(thumbTop) {
const ratio = thumbTop / (this.track.clientHeight - this.thumbHeight);
this.content.scrollTop = ratio * (this.content.scrollHeight - this.container.clientHeight);
}
animateThumb(targetTop) {
// 簡單線性動畫,生產環境建議用 requestAnimationFrame + easing
const startTop = this.thumb.offsetTop;
const duration = 200;
const startTime = performance.now();
const animate = (now) => {
const progress = Math.min((now - startTime) / duration, 1);
const currentTop = startTop + (targetTop - startTop) * progress;
this.thumb.style.top = currentTop + 'px';
this.syncContent(currentTop);
if (progress < 1) requestAnimationFrame(animate);
};
requestAnimationFrame(animate);
}
}
// 初始化
new CustomScrollbar('.scroll-container');
CSS 樣式要點
.scroll-container { position: relative; overflow: hidden; height: 300px; }
.scroll-content { position: absolute; top: 0; left: 0; right: 16px; bottom: 0; overflow: hidden; }
.scroll-track { position: absolute; top: 0; right: 0; bottom: 0; width: 12px; background: #eee; border-radius: 6px; }
.scroll-thumb { position: absolute; left: 2px; right: 2px; background: #999; border-radius: 4px; cursor: pointer; transition: background 0.2s; }
.scroll-thumb:hover { background: #666; }
無障礙與增強
- 添加
role="scrollbar"、aria-orientation="vertical"、aria-valuemin/max/now。
- 支持觸摸事件
touchstart/move/end 實現移動端拖拽。
- 內容變動時調用
updateGeometry() 重新計算。