如何限制容器鼠标拖拽调整方向及修复拖拽触发区域异常问题
解决方案
核心修改点
- 新增方向标记变量,仅修改当前拖拽方向的尺寸,不会同时改动宽高
- 修正坐标计算逻辑,避免伪元素导致的offset坐标偏移,解决全宽/全高拖拽区域失效问题
- 抽离触发尺寸配置,可统一调整拖拽可点击区域大小
完整修改后代码
HTML 部分(无修改)
<div id="styleChangeOuterTag"> <hr> <div id="styleOptionDetails"> </div> </div>
CSS 部分
#styleChangeOuterTag { position: relative; top: 0; left: 0; width: 300px; height: 300px; padding: 2vw 1.5vw; background-color: rgb(255, 245, 245); border: 2px solid rgb(255, 60, 255); border-radius: 3px; z-index: 5; user-select: none; } #styleChangeOuterTag::after { content: ''; background-color: #ccc; position: absolute; top: 0; right: 0; /* 此处宽度和JS中RESIZE_TRIGGER_SIZE保持一致 */ width: 10px; height: 100%; cursor: ew-resize; } #styleChangeOuterTag::before { content: ''; background-color: #ccc; position: absolute; bottom: 0; right: 0; width: 100%; /* 此处高度和JS中RESIZE_TRIGGER_SIZE保持一致 */ height: 10px; cursor: ns-resize; } #styleOptionDetails { border: 2px solid purple; border-radius: 3px; padding: 1vw; overflow: auto; }
JS 部分
const panel = document.getElementById("styleChangeOuterTag"); // 拖拽触发区域尺寸,和CSS中触发条的宽/高数值保持一致 const RESIZE_TRIGGER_SIZE = 10; let startX, startY, startWidth, startHeight; // 记录当前拖拽方向:width(右侧拉宽)/height(底部拉高)/null(未拖拽) let resizeDirection = null; function resize(e) { if (resizeDirection === 'width') { const dx = e.clientX - startX; panel.style.width = `${startWidth + dx}px`; } else if (resizeDirection === 'height') { const dy = e.clientY - startY; panel.style.height = `${startHeight + dy}px`; } } panel.addEventListener("mousedown", function(e) { const rect = panel.getBoundingClientRect(); // 计算鼠标相对于容器本身的真实坐标,不受伪元素/子元素影响 const relativeX = e.clientX - rect.left; const relativeY = e.clientY - rect.top; // 右侧拖拽触发 if (relativeX > panel.clientWidth - RESIZE_TRIGGER_SIZE) { resizeDirection = 'width'; startX = e.clientX; startWidth = panel.clientWidth; document.addEventListener("mousemove", resize); e.preventDefault(); } // 底部拖拽触发 else if (relativeY > panel.clientHeight - RESIZE_TRIGGER_SIZE) { resizeDirection = 'height'; startY = e.clientY; startHeight = panel.clientHeight; document.addEventListener("mousemove", resize); e.preventDefault(); } }); document.addEventListener("mouseup", function() { resizeDirection = null; document.removeEventListener("mousemove", resize); });
拖拽区域尺寸调整方法
需要修改可触发拖拽的灰色区域尺寸时,只需同步修改两个位置:
- JS代码中
RESIZE_TRIGGER_SIZE的数值,单位为px - CSS代码中
#styleChangeOuterTag::after的width属性、#styleChangeOuterTag::before的height属性,和上述数值保持一致即可
内容的提问来源于stack exchange,提问作者Yupma
相关产品推荐
相关产品推荐

