实现思路是使用js监听鼠标实现三个事件(鼠标按下mousedown,鼠标移动mousemove,鼠标放开mouseup),来绝对定位dom的位置
1 2 3 4 5 6 7 8 9 10
| <div class="drag" @mousedown="down" @mousemove="move" @mouseup="end" @touchstart.stop="down" @touchmove.stop="move" @touchend.stop="end" :style="{ top: position.y + 'px', left: position.x + 'px' }" > </div>
|
初始化默认值
1 2 3 4 5 6 7
| const dx, dy; ... position: { x: document.body.clientWidth, y: document.body.clientHeight } ...
|
还需要定义一个flags来标识鼠标是否被按下,只有按下才执行mousemove里面具体方法
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
| down (event) { this.flags = true const touch = event.touches ? event.touches[0] : event
dx = touch.clientX - event.target.offsetLeft dy = touch.clientY - event.target.offsetTop },
move (event) { if (this.flags) { const touch = event.touches ? event.touches[0] : event
this.position.x = touch.clientX - dx this.position.y = touch.clientY - dy
if (this.position.x < 0) { this.position.x = 0 } else if (this.position.x > screenWidth - touch.target.clientWidth) { this.position.x = screenWidth - touch.target.clientWidth } if (this.position.y < 0) { this.position.y = 0 } else if (screenHeight - touch.target.clientHeight - touch.clientY < 0) { this.position.y = screenHeight - touch.target.clientHeight }
document.addEventListener( 'touchmove', function () { event.preventDefault() }, false ) } },
end () { this.flags = false }
|