js 頁面上元素任意拖拽
阿新 • • 發佈:2018-11-30
function moveanyway () { // 獲取節點 var block = document.getElementById('myCoups') if (block) { var oW, oH // 繫結touchstart事件 block.addEventListener('touchstart', function (e) { var touches = e.touches[0] oW = touches.clientX - block.offsetLeft oH = touches.clientY - block.offsetTop // 阻止頁面的滑動預設事件 document.addEventListener('touchmove', defaultEvent, { passive: false }) }, false) block.addEventListener('touchmove', function (e) { var touches = e.touches[0] var oLeft = touches.clientX - oW var oTop = touches.clientY - oH if (oLeft < 10) { oLeft = 10 if (oTop <= 10) { oTop = 10 } else if (oTop >= document.documentElement.clientHeight - block.offsetHeight - 10) { oTop = document.documentElement.clientHeight - block.offsetHeight - 10 } } else if (oLeft > document.documentElement.clientWidth - block.offsetWidth - 10) { oLeft = (document.documentElement.clientWidth - block.offsetWidth - 10) if (oTop <= 10) { oTop = 10 } else if (oTop >= document.documentElement.clientHeight - block.offsetHeight - 10) { oTop = document.documentElement.clientHeight - block.offsetHeight - 10 } } else if (oTop < 10) { oTop = 10 } else if (oTop > document.documentElement.clientHeight - block.offsetHeight - 10) { oTop = document.documentElement.clientHeight - block.offsetHeight - 10 } block.style.left = oLeft + 'px' block.style.top = oTop + 'px' }, false) block.addEventListener('touchend', function () { document.removeEventListener('touchmove', defaultEvent, { passive: false }) }, false) } function defaultEvent (e) { e.preventDefault() }