用js写一个自定义滚动条
时间: 2024-04-07 13:30:17 浏览: 7
当然可以!以下是使用 JavaScript 和 CSS 来创建一个自定义滚动条的示例代码:
HTML:
```html
<div class="container">
<div class="content">
<!-- 这里放置你的内容 -->
</div>
<div class="scrollbar">
<div class="thumb"></div>
</div>
</div>
```
CSS:
```css
.container {
position: relative;
width: 300px;
height: 200px;
overflow: hidden;
}
.content {
width: 100%;
height: 100%;
overflow: auto;
}
.scrollbar {
position: absolute;
right: 0;
top: 0;
width: 8px;
height: 100%;
background-color: #f1f1f1;
}
.thumb {
background-color: #888;
width: 100%;
cursor: pointer;
}
```
JavaScript:
```javascript
const container = document.querySelector('.container');
const content = document.querySelector('.content');
const scrollbar = document.querySelector('.scrollbar');
const thumb = document.querySelector('.thumb');
thumb.style.height = container.clientHeight / content.scrollHeight * container.clientHeight + 'px';
thumb.addEventListener('mousedown', function(e) {
const startY = e.clientY;
const startTop = thumb.offsetTop;
function onMouseMove(e) {
const delta = e.clientY - startY;
let top = startTop + delta;
if (top < 0) {
top = 0;
} else if (top > container.clientHeight - thumb.clientHeight) {
top = container.clientHeight - thumb.clientHeight;
}
const scrollPercentage = top / (container.clientHeight - thumb.clientHeight);
content.scrollTop = scrollPercentage * (content.scrollHeight - container.clientHeight);
thumb.style.top = top + 'px';
}
function onMouseUp() {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
}
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
});
content.addEventListener('scroll', function() {
const scrollPercentage = content.scrollTop / (content.scrollHeight - container.clientHeight);
const top = scrollPercentage * (container.clientHeight - thumb.clientHeight);
thumb.style.top = top + 'px';
});
```
将这些代码放在你的 HTML 文件中,在容器元素中放置你的内容,并为其添加相应的 CSS 类。这样就可以创建一个自定义滚动条了,滚动条的样式可以根据需要进行自定义。