JavaScript

javascript自定义滚动条代码怎么写

小亿
108
2023-07-31 16:12:11
栏目: 编程语言

要自定义滚动条,你可以使用 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 样式进行调整来自定义滚动条的外观和行为。

0
看了该问题的人还看了