js drag Adopt simple closure implementation method
/**
* Created with JetBrains WebStorm.
* User: lsj
* Date: 12-11-24
* Time: 下午12:59
* To change this template use File | Settings | File Templates.
*/
var dragmanager=(function()
{
//Identifies the z-axis coordinate of the mobile element
var index_z=1 ;
//Current drag element
var drganow;
//Move identifier
var dragbegin=false;
//Distance from the left side of the div when the mouse is clicked
var relativex =0;
//The distance from the top of the div when the mouse is clicked
var relativey=0;
//Identifies whether the mouse has moved out
var isout=false;
return {
/* *
* Bind the mouse lift event to the document, mainly to prevent the mouse from moving too fast and jumping out of the el area
*/
bingDocOnMouseUp:function()
{
//Register the global onmouseup event, mainly to prevent the mouse from moving too fast and causing the mouse and el to be out of sync
document.onmouseup=function( e)
{
var ev = window.event || e;
if(isout && dragbegin)
{
//Change the relative position of the div
drganow.style.left = (ev.clientX-relativex) 'px';
drganow.style.top=(ev.clientY-relativey) 'px';
drganow.style.cursor='normal';
dragbegin= false;
isout=false;
}
}
},
/**
* Bind the event to the injected element
* @param el
*/
registerElementEv:function(element)
{
element .onmousedown=function(e)
{
var ev = window.event || e;
var clientx=ev.clientX;
var clienty= ev.clientY;
var left= parseInt(this.style.left.substring(0, this.style.left.indexOf("p")));
var top= parseInt(this.style.top.substring(0, this.style.top .indexOf("p")));
relativex=clientx-left;
relativey=clienty-top;
index_z ;
this.style.zIndex=index_z;
drganow=this ;
dragbegin=true;
}
element.onmousemove=function(e)
{
var ev = window.event || e;
//Start dragging
if(dragbegin)
{
//Change the relative position of the div
this.style.left= (ev.clientX-relativex) 'px';
this.style.top=(ev .clientY-relativey) 'px';
this.style.cursor='move';
}
}
element.onmouseout=function(e)
{
isout= true;
}
element.onmouseup=function(e)
{
var ev = window.event || e;
if(dragbegin)
{
// Change the relative position of the div
drganow.style.left= (ev.clientX-relativex) 'px';
drganow.style.top=(ev.clientY-relativey) 'px';
drganow. style.cursor='normal';
dragbegin=false;
}
}
}
}
})();
1. It is implemented in the form of a closure to facilitate later maintenance. All variables required for the movement process are transferred into the gridmanager
2. During the dragging process, the mouse moves too fast and the moving element cannot keep up with the movement of the mouse, so it needs to be registered. document.oumouseup event, the switch of this event is triggered by the onmouseout event of the moving element
3. The browser's own onmousemove select event may be triggered during the dragging process, which can be blocked. IE is onmousemove="document .selection.empty()"