原生JS拖拽运用onmousedown,onmousemove,onmouseup等事件来实现拖拽,难点在于在拖拽时会同时触发点击事件。
思路:
定义一个变量var isDrag
在onmousedown时isDrag = false
在onmousemove时isDrag = true, 同时需要判断鼠标点击偏移量小时,isDrag = false
在click事件时根据isDrag来判断是否允许点击事件
以下具体代码:
拖拽事件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| var isDrag = false function dragEvent (ele) { if (!ele) return var _self = this document.ondragstart = function(ev) { var event = event || window.event event.preventDefault(); }; document.ondragend = function(ev) { var event = event || window.event event.preventDefault(); }; ele.onmousedown = function(event){ isDrag = false var event = event || window.event; var diffX = event.clientX - ele.offsetLeft; var diffY = event.clientY - ele.offsetTop; var startDotx = event.screenX; var startDoty = event.screenY; if(typeof ele.setCapture !== 'undefined'){ ele.setCapture(); } document.onmousemove = function(event){ isDrag = true var event = event || window.event; var moveX = event.clientX - diffX; var moveY = event.clientY - diffY; if (startDotx && startDoty) { let difX = event.screenX - startDotx let difY = event.screenY - startDoty let difD = Math.sqrt(difX * difX + difY * difY) if (difD >= 0 && difD < 5) { isDrag = false } } if(moveX < 0){ moveX = 0 }else if(moveX > window.innerWidth - ele.offsetWidth){ moveX = window.innerWidth - ele.offsetWidth } if(moveY < 0){ moveY = 0 }else if(moveY > window.innerHeight - ele.offsetHeight){ moveY = window.innerHeight - ele.offsetHeight } let iconWidth = ele.style.width.replace('px', '') if (moveY > window.innerHeight - iconWidth) { moveY = window.innerHeight - iconWidth } ele.style.bottom = 'auto' ele.style.left = moveX + 'px'; ele.style.top = moveY + 'px' } document.onmouseup = function(event){ document.onmousemove = null; document.onmouseup = null; if(typeof ele.releaseCapture != 'undefined'){ ele.releaseCapture() } } } }
|
点击事件
1 2 3 4 5
| ele.addEventListener('click', function (e) { e.stopPropagation() if (isDrag) return })
|