``javascript,class ScrollBar {, constructor(container) {, this.container = container;, this.init();, },, init() {, const scrollbar = document.createElement('div');, scrollbar.style.width = '10px';, scrollbar.style.background = '#ddd';, scrollbar.style.position = 'absolute';, scrollbar.style.right = '0';, scrollbar.style.top = '0';, scrollbar.style.bottom = '0';, this.scrollbar = scrollbar;, this.container.appendChild(this.scrollbar);,, this.handle = document.createElement('div');, this.handle.style.width = '50px';, this.handle.style.background = '#888';, this.handle.style.position = 'absolute';, this.handle.style.cursor = 'grab';, this.handle.style.userSelect = 'none';, this.handle.style.height = '20px';, this.handle.style.borderRadius = '10px';, this.handle.style.marginTop = '-10px';, this.handle.addEventListener('mousedown', this.startDrag.bind(this));, this.scrollbar.appendChild(this.handle);,, this.container.addEventListener('scroll', () => {, const maxScrollTop = this.container.scrollHeight this.container.clientHeight;, const scrollRatio = this.container.scrollTop / maxScrollTop;, this.handle.style.top =
${scrollRatio * (this.container.clientHeight this.handle.offsetHeight)}px;, });,, this.updateHandleSize();, },, startDrag(event) {, event.preventDefault();, const startY = event.clientY;, const startTop = parseInt(this.handle.style.top, 10);, const containerRect = this.container.getBoundingClientRect();, const maxScrollTop = this.container.scrollHeight this.container.clientHeight;, const handleHeight = this.handle.offsetHeight;,, const onMouseMove = (moveEvent) => {, const deltaY = moveEvent.clientY startY;, const newTop = Math.min(Math.max(startTop + deltaY, 0), containerRect.height handleHeight);, const scrollRatio = newTop / (containerRect.height handleHeight);, this.container.scrollTop = scrollRatio * maxScrollTop;, };,, const onMouseUp = () => {, document.removeEventListener('mousemove', onMouseMove);, document.removeEventListener('mouseup', onMouseUp);, };,, document.addEventListener('mousemove', onMouseMove);, document.addEventListener('mouseup', onMouseUp);, },, updateHandleSize() {, const containerHeight = this.container.clientHeight;, const contentHeight = this.container.scrollHeight;, const handleHeight = Math.max((contentHeight / containerHeight) * containerHeight, 30); // Minimum handle height of 30px, this.handle.style.height =
${handleHeight}px;, },},,// 使用示例,const myContainer = document.getElementById('myContainer');,new ScrollBar(myContainer);,
``