Home > front end >  Solve the problem of custom div drag-and-drop caton
Solve the problem of custom div drag-and-drop caton

Time:12-07

Today with reference to other people's blog on the net, the drag effect of di, mainly using the window onm ousemove attribute to realize positioning, and then modify the need to move the element of absolute positioning, but in the end, it was found that drag and drop a card to use, mainly is fast, the mouse from elements follow the mouse effect disappeared after the target element, element to stop movement, experience is not good, see a lot of have no solution to solve the problem, finally, debugging is simple to solve the problem, now share with you, help you later from the pit...

Code:

//div drag
The export function divMove (that, childId, ParentId, e) {

//lock, prevent drag not smooth
If (that) the lock) {
return;
}

//set the message box can drag
Let the title=document. GetElementById (childId);
Let the main=document. GetElementById (ParentId);

//move control variables
Let isStartMove=false;
Let x=0;
Let y=0;
Let l=0;
Let t=0;

The title. The onm ousedown=(e)=& gt; {
That the lock=true;
Let event=e | | window. The event;
IsStartMove=true;
The title. The style. The cursor='move';
X=event. ClientX;
Y=event. ClientY;
L=main. OffsetLeft
T=main. OffsetTop;
}
Window. The onm ousemove=(e)=& gt; {
if (! IsStartMove) {
return;
}
Var event=e | | window. The event;

Let ln=event. ClientX - (x - l);
Let tn=event. ClientY - (y, t);
The main. Style. Left=ln + 'px';
The main. Style. The top=tn + 'px';
}

The title. The onm ouseup=()=& gt; {
That the lock=false;
IsStartMove=false;
The title. The style. The cursor='default';
}

};

Pulled out a method above, usage scenario is multiple place on the page by dragging child elements are needed to change the position of the parent element, the element to initialize drag and drop method is the onm ouseEnter event triggered by the target element, through debugging code found that when the mouse click left key drag and drop quickly out of the target element, don't know why will trigger the onm ouseEnter event, lead to the left key press state second trigger onm ouseEnter isStartMove whether will follow the mouse state variables set to false, so stop tuo drag

Find the problem reason, can be very simple to solve the problem, in the component class this. Set the global switch lock, false by default, when the mouse to press set to true, fold is again reducing false, equivalent to add a lock to drag and drop events, when a drag and drop event did not complete, do not allow the initialized again, which can solve the problem of a single element drag-and-drop caton, also solved the interference between different elements, now drag and drop is very smooth, nice
  • Related