你的意思是拖拽的过程中不让子元素拖出父元素边界吗?如果是的话,可以参考下面jq代码实现,主要是设置做大可移动的宽高//拖拽 $.fn.wmDrag = function(){ return this.each(function(index, oDiv){ oDiv.draggable = false oDiv.style.cursor = 'move' oDiv.onmousedown = function (e) { if(e.button == 2)return; //过滤右键按下事件 var omousemove = document.onmousemove, omouseup = document.onmouseup; //鼠标按下,计算当前元素距离可视区的距离 var disX = e.clientX, disY = e.clientY, sty = window.getComputedStyle(oDiv), transition = sty.transition, left = parseInt(sty.left), top = parseInt(sty.top), $parent = $(oDiv).parent(), //maxL = document.body.clientWidth - parseInt(sty.width), maxL = $parent.width() - parseInt(sty.width), //maxT = document.body.clientHeight - parseInt(sty.height); maxT = $parent.height() - parseInt(sty.height); oDiv.style.transition = 'none' oDiv.style.left = left + 'px' oDiv.style.top = top + 'px' oDiv.style.bottom = oDiv.style.right = 'auto' document.onmousemove = function (e) { //通过事件委托,计算移动的距离 var l = e.clientX - disX; var t = e.clientY - disY; l = left + l l = l > maxL ? maxL : l < 0 ? 0 : l t = top + t t = t > maxT ? maxT : t < 0 ? 0 : t //移动当前元素 oDiv.style.left = l + 'px'; oDiv.style.top = t + 'px'; }; document.onmouseup = function (e) { document.onmousemove = omousemove; document.onmouseup = omouseup; oDiv.style.transition = transition sty = window.getComputedStyle(oDiv) left = parseInt(sty.left) top = parseInt(sty.top) let right = parseInt(sty.right), bottom = parseInt(sty.bottom) if(left > right){ oDiv.style.right = right + 'px' oDiv.style.left = 'auto' } if(top > bottom){ oDiv.style.bottom = bottom + 'px' oDiv.style.top = 'auto' } }; }; }) }
你的意思是拖拽的过程中不让子元素拖出父元素边界吗?如果是的话,可以参考下面jq代码实现,主要是设置做大可移动的宽高