要自定義滾動條,你可以使用 CSS 和 JavaScript 來實現。以下是一個簡單的示例代碼:
HTML:
<div class="container">
<div class="content">
<!-- 內容 -->
</div>
</div>
CSS:
.container {
width: 200px;
height: 300px;
overflow: auto;
position: relative;
}
.content {
width: 100%;
height: 1000px;
}
.scrollbar {
position: absolute;
right: 0;
top: 0;
width: 6px;
background-color: #ccc;
border-radius: 3px;
opacity: 0;
transition: opacity 0.3s;
cursor: pointer;
}
.scrollbar:hover {
opacity: 1;
}
.thumb {
background-color: #888;
border-radius: 3px;
width: 100%;
position: absolute;
top: 0;
left: 0;
}
JavaScript:
const container = document.querySelector('.container');
const content = document.querySelector('.content');
const scrollbar = document.createElement('div');
const thumb = document.createElement('div');
scrollbar.classList.add('scrollbar');
thumb.classList.add('thumb');
container.appendChild(scrollbar);
scrollbar.appendChild(thumb);
// 更新滾動條位置
const updateScrollbar = () => {
const contentHeight = content.clientHeight;
const containerHeight = container.clientHeight;
const scrollTop = container.scrollTop;
const scrollRatio = scrollTop / (contentHeight - containerHeight);
const scrollbarHeight = containerHeight * containerHeight / contentHeight;
thumb.style.height = `${scrollbarHeight}px`;
thumb.style.transform = `translateY(${scrollRatio * (containerHeight - scrollbarHeight)}px)`;
};
// 滾動條拖動事件
thumb.addEventListener('mousedown', (e) => {
const startY = e.clientY;
const thumbTop = thumb.getBoundingClientRect().top;
const containerTop = container.getBoundingClientRect().top;
const maxScrollTop = content.clientHeight - container.clientHeight;
const mouseMoveHandler = (e) => {
const deltaY = e.clientY - startY;
const thumbPosition = thumbTop - containerTop + deltaY;
const scrollRatio = thumbPosition / (container.clientHeight - thumb.clientHeight);
container.scrollTop = scrollRatio * maxScrollTop;
};
const mouseUpHandler = () => {
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
};
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
});
// 監聽內容滾動事件
container.addEventListener('scroll', updateScrollbar);
// 初始化滾動條
updateScrollbar();
這段代碼會添加一個自定義滾動條到容器 .container
中,并監聽滾動事件更新滾動條的位置。你可以根據需要對 CSS 樣式進行調整來自定義滾動條的外觀和行為。