In the online map project, when the marker Point binding event, because there is a click event click, while there is a drag dragend event, there is no major flaw, that is, when the user clicked, sometimes this would like to be clicked, but he triggered the drag event, Create a bad user experience
Cause of the bug
一个完整的click事件是包含 mousedown,mouseup两个事件的,而拖拽一个元素时,包含下面三个事件:mousedown,mousemove,mouseup,所以我们在拖拽一个元素结束后,如果此元素上面绑定了点击事件, 就会同时触发元素的点击事件,或者用户只是想触发点击事件,但是又同时出发了drag事件,用户体验度不好。
Solution Ideas
仔细比较拖拽与点击事件,发现拖拽事件多了一个mousemove,我们可以从这个mousemove入手,点击事件 时mousedown与mouseup触发时鼠标没有移动,而拖拽时鼠标移动了一定的距离,具体体现在px上。
Solutions
可以设定一个clickFlag变量,通过clickFlag来确定mousedown与mouseup到底是触发了点击事件还是 拖动事件:mousedown时记录下鼠标的位置x1,y1,mouseup时记录下鼠标的位置x2,y2,判断两次位置 是否一样或是相差小于一个定值(设为7px):d = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2))
当d=0或是小于7时,即可认定用户没有拖拽。此时clickFlag为true,可以触发点击事件。
代码:
1 varx1,x2,y1,y2,dragflag=false;2 //Drag End event for maker3Marker.addeventlistener ("Dragend",function(){4 varMe= This;5Attribute (Dragflag, This)6 });7Marker.addeventlistener ("MouseDown",function(e) {8x1=E.clientx;9y1=E.clienty;TenConsole.log (x1+ ";") +y1); One});//MouseDown recording mouse position 1 AMarker.addeventlistener ("MouseUp",function(e) { -X2=E.clientx; -Y2=E.clienty; theConsole.log (x2+ ";") +y2); - var_val=math.sqrt ((x2-x1) * (x2-x1) + (y2-y1) * (y2-y1)); - Console.log (_val); - //Judging + if(_val>=0&&_val<=2){ -dragflag=true; +}Else{ Adragflag=false; at } -});//MouseUp recording mouse position 2
Fix a bug that triggers a click event while JavaScript is dragging