Some time ago, I wrote a simple div drag effect. Unexpectedly, I needed a similar requirement in the project yesterday, so I used it. However, I ran into problems in the mobile terminal, and the three events used in dragging, mousedown, Mousemove and Mouseup, did not work in the mobile terminal. After all, there is no mouse on the mobile terminal. After checking the data, it is found that the corresponding events on the mobile terminal are respectively TouchStart, TouchMove and TouchEnd events. Touch [0]. ClientX and Event.touches [0]. ClientY.

Here is how to achieve this effect, first look at the effect:

PC

The mobile terminal

First, analyze a dragging process. Take PC as an example. First, the mouse is pressed down (mousedown event), then moved (Mousemove event), and finally released (Mouseup event). And then you need to record the current coordinates of the mouse, and the current offset of the div, and when the mouse starts to move, record the current coordinates of the mouse, take the current coordinates of the mouse minus the coordinates when the mouse is down plus the offset of the div when the mouse is down and that’s how far the div is now from the parent element, Changes the flag to mouse released when mouse is released.

Here’s the code:

var flag = false; Var cur = {var nx,ny,dx,dy,x,y; Function down(){flag = true; // Confirm mouse press cur.x = event.clientx; Cur. y = event. ClientY; Dx = div2.offsetLeft; Dy = div2.offsetTop; Function move(){if(flag){nx = event.clientx - cur.x; function move(){if(flag){ Ny = event.clienty - cur.y; X = dx+nx; // Div's offset in the X-axis plus the distance the mouse moves in the X-axis y = dy+ny; Div2.style. left = x+"px"; div2.style.top = y +"px"; Function end(){flag = false; // Mouse release}Copy the code

Then add the event to the div, and let’s look at what you need to do on the mobile side. First, the event is different. Just add touchatArt, TouchMove, touchEnd on the mobile side. Touches [0]. ClientX and Event.touches [0]. ClientY. Use Event.touches if you are mobile:

var touch ;
if(event.touches){
    touch = event.touches[0];
}else {
    touch = event;
}Copy the code

Also note that the mobile page slides automatically when you drag the div on the mobile side, so you need to add a function to the page that blocks the default event on touchMove.

Here is the entire code, which can be simulated for mobile testing in Chrome, click here to see:

#div1{height: 1000px; } #div2{ position: absolute; top:0; left:0; width: 100px; height: 100px; background: #bbbbbb; }
      
Copy the code

If you have any questions, please point out, thank you!