JavaScript implements drag-and-drop effects on elements (1/2)

Source: Internet
Author: User

The drag of a DOM node is a simple JavaScript effect, often called a drag-and-drop, that is, Drag-and-drop.

Drag and drop mainly involves three processes:

Click on the object you want to drag and drop to record the mouse relative to the drag object (left and top values) coordinates
During mouse movement events, the left and top values of the object are constantly changed, which results in mouse follow up.
Mouse loosens events, lifting mouse movement events.

Implement drag-and-drop related HTML and CSS

Here is the HTML code structure to drag and drop implementations:

The code is as follows Copy Code

<div class= "Parent" >
<div id= "Drag" ></div>
</div>

The following are the relevant CSS

The code is as follows Copy Code

. Parent {
position:relative;
}
#drag {
Position:absolute;
top:20px;
left:40%;
width:150px;
height:150px;
Cursor:move;
}

Here is a general implementation of drag-and-drop method, it is a good description of the three-drag process:

The code is as follows Copy Code
var objmove = function () {
Get the object to move
var mine = document.getElementById (' drag '),
Used to store the mouse's position relative to the object
dx=dy=0;
Mine.onmousedown = function (e) {
var e = e | | Window.event,
x = E.offsetleft,
y = e.offsettop;
Parseint converts the characters of the "5px" class to 5 www.111cn.net

DX = X-parseint (GetStyle (this, ' left ')),
DY = Y-parseint (GetStyle (this, ' top '));
Document.onmousemove = function (e) {
var e = e | | Window.event,
x = E.offsetleft,
y = e.offsettop;
Mine.style.left = x-dx + ' px ';
Mine.style.top = y-dy + ' px ';
};
Document.onmouseup = function () {
When the mouse is loosened, the MouseMove and so on is lifted
Document.onmousemove = null;
Document.onmouseup = null;
};
};
};
Window.onload = Objmove;
Gets the style currently applied by the Obj object
function GetStyle (obj,style) {
if (window.getComputedStyle) {
Standard browser
Return getComputedStyle (Obj,null) [style];
} else {
Browsers for the following versions of IE8 and IE8
return Obj.currentstyle[style];
}
};

The GetStyle function in the above code is to get the style that the node eventually applies to.
More Perfect drag and drop

The following first write some relevant code, GetStyle has been introduced above, so do not repeat the description.

In drag, the binding and unbind of events are involved. Because IE is not the same as the method of event binding and lifting in standard browsers, it is a special declaration of an object eventutil.

The code is as follows Copy Code
var eventutil = {
Addhandler:function (element, type, handler) {
Binding events
if (Element.addeventlistener) {
Element.addeventlistener (type, handler, false);
else if (element.attachevent) {
Element.attachevent (' on ' +type,handler);
} else {
element[' on ' +type] = handler;
}
},
Removehandler:function (Element,type,handler) {
Unbind Event
if (Element.removeeventlistener) {
Element.removeeventlistener (Type,handler,false);
}else if (element.detachevent) {
Element.detachevent (' on ' +type,handler);
}else {
element[' on ' +type] = null;
}
}
};

The following is a relatively complete function of drag-and-drop functions based on Eventutil and GetStyle. First get the code:

The code is as follows Copy Code
var eventutil = {
Event Object
};
function GetStyle (node,style) {
Get final style
};
function drag (obj) {
var islimit = Obj.islimit | | False
ParentNode = Obj.currentNode.offsetParent,
CurrentNode = Obj.currentnode,
StartDrag = Obj.startdrag,
Ondrag = Obj.ondrag,
EndDrag = Obj.enddrag,
LIMITX = OBJ.LIMITX | | False
limity = Obj.limity | | False
Retobj = {},
x = 0,
y = 0;
Eventutil.addhandler (Obj.currentnode, ' MouseDown ', function (e) {
Binding events
var e = e | | Window.event,
_x= E.pagex | | E.x,
_y = E.pagey | | E.Y,
Bdwidth=[],
dx = dy = 0;
Bdwidth =[
parseint (GetStyle (parentnode, ' bordertopwidth ')),
parseint (GetStyle (parentnode, ' borderrightwidth ')),
parseint (GetStyle (parentnode, ' borderbottomwidth ')),
parseint (GetStyle (parentnode, ' borderleftwidth '))
];
The origin coordinate of the moving object (relative to Document.body)
var origin = [
Parentnode.offsetleft,
Parentnode.offsettop,
PARENTNODE.OFFSETWIDTH-BDWIDTH[1]-BDWIDTH[3],
PARENTNODE.OFFSETHEIGHT-BDWIDTH[0]-BDWIDTH[2]
],//defines a new origin coordinate x,y,w,h
Mousepos = [_x-origin[0],_y-origin[1]],//mouse clicks relative origin coordinates
CurPos = [
Currentnode.offsetleft,
Currentnode.offsettop,
Currentnode.offsetwidth,
Currentnode.offsetheight
],//moving objects relative to Origin coordinates x,y,w,h
Limitsection = [' Notlimit ', ' notlimit ', ' notlimit ', ' notlimit ']; The area that the object can move Minx,maxx,miny,maxy
if (StartDrag && typeof StartDrag = = ' function ') {
Retobj = StartDrag (Currentnode,curpos);
if (retobj) {
LIMITX = (Retobj.limitx = = undefined)? LimitX:retObj.limitX;
Limity = (retobj.limity = = undefined)? LimitY:retObj.limitY;
Islimit = (Retobj.islimit = = undefined)? isLimit:retObj.isLimit;
}
}
DX = mousepos[0]-curpos[0];
DY = mousepos[1]-curpos[1];
if (LIMITX) {//To define the initialization limitsection based on the given region
if (Limitx[0]!= undefined) {
Limitsection[0] = limitx[0];
}
if (limitx[1]!= undefined) {
LIMITSECTION[1] = limitx[1];
}
}
if (limity) {
if (Limity[0]!= undefined) {
LIMITSECTION[2] = limity[0];
}
if (limity[1]!= undefined) {
LIMITSECTION[3] = limity[1];
}
}
if (islimit) {//Determine if you want to restrict to the parent element
for (var i=0; i<limitsection.length; i++) {
if (limitsection[i] = = ' Notlimit ') {
switch (i) {
Case 0:
Limitsection[i] = 0;
Break
Case 1:
Limitsection[i] = origin[2]-curpos[2];
Break
Case 2:
Limitsection[i] = 0;
Break
Case 3:
Limitsection[i] = origin[3]-curpos[3];
Break
}
} else {
switch (i) {
Case 0:
Limitsection[i] = Math.max (limitsection[i],limitx[0]);
Break
Case 1:
Limitsection[i] = math.min (origin[2]-curpos[2],limitx[1]);
Break
Case 2:
Limitsection[i] = Math.max (limitsection[i],limity[0]);
Break
Case 3:
Limitsection[i] = math.min (origin[3]-curpos[3],limity[1]);
Break
}
}
}
}
var moumove = function (e) {
var e = e | | Window.event,
_x= (E.pagex | | e.x)-ORIGIN[0],
_y = (E.pagey | | e.y)-ORIGIN[1];
x = _X-DX;
y = _y-dy;
for (Var i=0;i<limitsection.length;i++) {
if (Limitsection[i]!= ' Notlimit ') {
switch (i) {
Case 0:
x = Math.max (X,limitsection[i]);
Break
Case 1:
x = Math.min (X,limitsection[i]);
Break
Case 2:
y = Math.max (y, limitsection[i]);
Break
Case 3:
y = math.min (y, limitsection[i]);
Break
}
}
}
CurrentNode.style.left = x + ' px ';
CurrentNode.style.top = y + ' px ';
if (Ondrag && typeof Ondrag = = ' function ') {
Ondrag (Currentnode,[x,y]);
}
Prevents the mouse from moving the contents of the process from being selected www.111Cn.net
return false;
};
Eventutil.addhandler (document, ' MouseMove ', moumove);
var mouup = function () {
if (EndDrag && typeof EndDrag = = ' function ') {
EndDrag (Currentnode,[x,y]);
}
Eventutil.removehandler (document, ' MouseMove ', moumove);
Eventutil.removehandler (document, ' MouseUp ', mouup);
};
Eventutil.addhandler (document, ' MouseUp ', mouup);
return false;
});
}

Passing an object to the function drag can limit the drag area. The standard parameter format is as follows:

The code is as follows Copy Code
var obj = {
CurrentNode:document.getElementById (' Mine '),//DOM node to move
Islimit: ',//whether to lock the current element into the parent node
LIMITX: [],//array, limit the horizontal coordinates of the moving object, can be empty, or you can set only one coordinate
Limity: [],//array, restricting the cocked coordinates of the moving object
Startdrag:function () {},//Start dragging the executed function
Ondrag:function () {},//function performed during drag-and-drop
Enddrag:function () {}//callback function
}

CurrentNode is required in object parameters, and several other parameters are settings that can be selected as needed.

Islimit: Value can be true or False (default). When True, indicates that the DIV is restricted to its location.
LIMITX: An array of values that can be 1 or 2 in length. The first value of the array represents the leftmost area boundary of the move, and the second value represents the rightmost region boundary. You can set only the first value, or the second value.
Limity: Similar to LIMITX, the main limit is the vertical direction.
StartDrag: is a function that executes when you start dragging. You can have two parameters, the first parameter is a DOM node representing CurrentNode, and the second parameter is a 4-length array that represents the left, top, width, height of the currentnode. Alternatively, StartDrag can return an object that can contain Islimit, LIMITX, and limity to redefine the zone.
Ondrag: Is the function that is executed during the drag and drop process, and the EndDrag is executed when the drag completes. They can all pass two parameters, the first parameter represents CurrentNode, and the second parameter is an array that represents the left and top of the current currentnode.

Home 1 2 last page
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.