js 页面上元素任意拖拽

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()

}

 

你可能感兴趣的:(前端)