Last active
February 17, 2023 08:21
-
-
Save zbo2018/d50872fa8e206df4277c4b2810989460 to your computer and use it in GitHub Desktop.
拖拽动作,不触发点击事件
拖动与点击事件冲突解决
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
拖动与点击事件冲突解决 | |
问题: | |
有些用户的鼠标非常灵敏,点击的时候会偏移。出现轻微的拖拽操作 | |
思路1: | |
点击到移动的时间间隔< 150ms: 点击事件 | |
点击到移动的时间间隔>=150ms: 拖拽事件 | |
解决办法: | |
mousedown时记录时间t1全局变量, | |
mousemove时记录时间t2局部变量, | |
mouseup时记录时间t3局部变量, | |
mousemove中 | |
if(t2-t1<150)属于点击:不执行操作 | |
if(t2-t1>=150)属于拖拽:执行拖拽中逻辑 | |
mouseup中 | |
if(t3-t1<150)属于点击:执行点击逻辑 | |
if(t3-t1>=150)属于拖拽:执行拖拽逻辑 | |
重置t1全局变量 | |
思路2: | |
点击与移动的像素距离< 7:点击事件 | |
点击与移动的像素距离>=7:拖拽事件 | |
解决办法: | |
mousedown时记录下鼠标的位置x1,y1全局变量 | |
mousemove时记录下鼠标的位置x2,y2局部变量 | |
mouseup时记录下鼠标的位置x3,y3局部变量 | |
判断两次位置--是否一样或是相差小于一个定值(设为7px): | |
d = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) | |
d = Math.sqrt((x1-x3)*(x1-x3)+(y1-y3)*(y1-y3)) | |
当d=0或是小于7时,认定用户没有拖拽。属于点击 | |
当d>=7时,认定用户有拖拽。属于拖拽 | |
mousemove中 | |
if(d==0||d<7)属于点击:不执行操作 | |
if(d>=7)属于拖拽:执行拖拽中逻辑 | |
mouseup中 | |
if(d==0||d<7)属于点击:执行点击逻辑 | |
if(d>=7)属于拖拽:执行拖拽逻辑 | |
重置x1,y1全局变量 | |
存在的问题: | |
某些框架只有鼠标在图形元素上时才触发mousemove事件。 | |
当图形元素很小或是一条线时,鼠标很容易移出元素。不再触发mousemove、mouseup | |
导致通过距离无法判断是哪种操作。 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
页面上点击一个元素,最少三个事件会被触发,事件发生顺序: | |
1、mousedown,按下鼠标键的时候 | |
2、mouseup,松开鼠标键的时候 | |
3、click,当一个mousedown和一个mouseup都在这个元素上被检测到的时候发生 | |
功能: | |
元素上同时绑定:鼠标点击、拖拽事件 | |
要求: | |
拖拽的时候不执行点击逻辑! | |
分析: | |
希望拖拽动作后,不触发点击事件,单纯绑定click事件是不行的! | |
可以使用mousedown、mousemove、mouseup来描述拖拽和鼠标点击事件。 | |
mousedown-mousemove-mouseup,为拖拽事件; | |
mousedown-mouseup,为点击事件。 | |
解决: | |
通过flag判断是不是进行了move操作,一旦进行则mouseup中的函数体不执行即可,代码如下: | |
var ifDrag = false; | |
map.addEventListener("mousedown", function () { | |
ifDrag = false; | |
}) | |
map.addEventListener("mousemove", function () { | |
ifDrag = true; | |
}) | |
map.addEventListener("mouseup", function (type, evt) { | |
//判断是否有拖拽动作 | |
if (ifDrag) { | |
//拖拽逻辑 | |
}else { | |
//点击逻辑 | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
父元素的拖动和子元素的点击事件怎么解决冲突,在拖动时,执行了父元素的click,事件传递到子元素,也执行了子元素的click