1:先理解clientY pageY screenY layerY offsetY的区别
1:clientY 指的是距离可视页面左上角的距离
2:pageY 指的是距离可视页面左上角的距离(不受页面滚动影响)
3:screenY 指的是距离屏幕左上角的距离
4:layerY 指的是找到它或它父级元素中最近具有定位的左上角距离
5:offsetY 指的是距离它自己左上角的距离
2:思路
1:onmousedown:鼠标按下事件
2:onmousemove:鼠标移动事件
3:onmouseup:鼠标抬起事件
基本原理就是根据鼠标的移动来移动被拖拽的元素。鼠标的移动也就是x、y坐标的变化;元素的移动就是style.position的 top和left的改变。当然,并不是任何时候移动鼠标都要造成元素的移动,而应该判断鼠标左键的状态是否为按下状态,是否是在可拖拽的元素上按下。
<template>
<div class="drag">
<div id="lucky"
@mousedown="down" @touchstart="down"
@mousemove="move" @touchmove="move"
@mouseup="end" @touchend="end" @click="click" style="position: relative">
</div>
</div>
</template>
<script>
export default {
name: "drag",
data() {
return {
flags: false,
position: {
x: 0