蓝桉云顶

Good Luck To You!

你想知道如何实现一个JavaScript滚动条插件吗?

``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);,``
<< 1 >>
«    2024年12月    »
1
2345678
9101112131415
16171819202122
23242526272829
3031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接