如何计算元素滚动高度,实现鼠标在自定义滚动条移动时控制下拉菜单滚动
CSS修改(隐藏默认滚动条)
替换原有.menu-items-container的overflow: hidden属性,添加滚动条隐藏兼容样式:
.menu-items-container { background: dodgerblue; width: 90%; /* 替换原有overflow: hidden */ overflow-y: auto; max-height: 360px; /* 兼容Firefox隐藏滚动条 */ scrollbar-width: none; /* 兼容IE/Edge隐藏滚动条 */ -ms-overflow-style: none; } /* 兼容Chrome/Safari等Webkit内核浏览器隐藏滚动条 */ .menu-items-container::-webkit-scrollbar { display: none; }
JS修改(修正自定义滚动条拖拽逻辑)
删除原有错误的scrollbarConatiner.addEventListener("mousemove", ...)相关代码,替换为如下完整拖拽逻辑:
// 拖拽状态标记 let isScrollDragging = false; // 鼠标按下滚动条区域时启动拖拽 scrollbarConatiner.addEventListener('mousedown', function(e) { isScrollDragging = true; e.preventDefault(); }); // 鼠标移动时计算滚动位置 document.addEventListener('mousemove', function(e) { if (!isScrollDragging) return; // 计算鼠标在滚动条容器内的相对偏移 const containerRect = scrollbarConatiner.getBoundingClientRect(); let mouseY = e.clientY - containerRect.top; // 限制偏移范围,避免滚动条拖出容器 const scrollbarHeight = document.querySelector('.scrollbar').offsetHeight; const maxBarOffset = scrollbarConatiner.offsetHeight - scrollbarHeight; mouseY = Math.max(0, Math.min(mouseY, maxBarOffset)); // 按比例映射到内容的完整滚动范围 const contentScrollableHeight = menuItemsContainer.scrollHeight - menuItemsContainer.clientHeight; const scrollRatio = mouseY / maxBarOffset; menuItemsContainer.scrollTop = scrollRatio * contentScrollableHeight; }); // 鼠标松开/离开页面时结束拖拽 document.addEventListener('mouseup', function() { isScrollDragging = false; }); document.addEventListener('mouseleave', function() { isScrollDragging = false; });
原代码问题根源:直接将鼠标偏移量赋值给内容的scrollTop,没有做滚动比例映射,同时没有绑定正确的拖拽触发事件,且存在类名、属性名拼写错误导致逻辑失效。
内容的提问来源于stack exchange,提问作者JSX
相关产品推荐
相关产品推荐

