拖拽容器
//parent 在此容器移动
//child 移动的容器
//move_target 鼠标点击起作用容器,在child中
drag_move(parent,child,move_target){ // console.log(parent,child, move_target) child.onmousedown = function(ev) { // console.log('mousedown') var oEvent = ev; // 默认事件,这里要阻止 oEvent.preventDefault(); var disX = oEvent.clientX - move_target.offsetLeft; var disY = oEvent.clientY - move_target.offsetTop; parent.onmousemove = function(ev) { oEvent = ev; oEvent.preventDefault(); var x = oEvent.clientX - disX; var y = oEvent.clientY - disY; // console.log(x,y) // 图形移动的边界判断 // x = x <= 0 ? 0 : x; // x = x >= window.innerWidth - parent.offsetWidth ? window.innerWidth - parent.offsetWidth : x; // y = y <= 0 ? 0 : y; // y = y >= window.innerHeight - parent.offsetHeight ? window.innerHeight - parent.offsetHeight : y;
//本文是在vue环境,原生js环境要clearTimeout(timer),然后设置定时器 var timer = setTimeout()
setTimeout(()=>{ move_target.style.left = x + 'px'; move_target.style.top = y + 'px'; },20) } // 取消移动事件,防止移动过快触发鼠标移出事件,导致鼠标弹起事件失效 parent.onmouseleave = function() { parent.onmousemove = null; parent.onmouseup = null; } // 鼠标弹起后停止移动 parent.onmouseup = function() { parent.onmousemove = null; parent.onmouseup = null; } } },