How to drag with JavaScript
Javascript is characterized by Dom processing and web page effects. In most cases, we only use the simplest functions of this language, such as creating image carousel/Webpage tabs.ArticleIt will show you how to drag and drop your webpage.
There are many reasons to add the drag-and-drop function to your website. The simplest one is data restructuring. for example, if you have a sequence of content for user sorting, You need to input each entry or select it using select. Instead of dragging the preceding method. maybe your website also needs a navigation window that users can drag! These effects are simple: you can easily implement them!
Dragging on a webpage is not very complicated. First, you need to know the mouse coordinates. Second, you need to know that the user clicks a webpage element and implements dragging. Finally, we need to move this element.
Get mouse movement information
First, we need to get the coordinates of the mouse. we can add a User Function to document. onmousemove:
Document. onmousemove = mousemove;
Function mousemove (EV ){
Ev = EV | window. event;
VaR mousepos = mousecoords (EV );
}
Function mousecoords (EV ){
If (EV. pagex | eV. Pagey ){
Return {X: eV. pagex, Y: eV. Pagey };
}
Return {
X: eV. clientx + document. Body. scrollleft-document. Body. clientleft,
Y: eV. clienty + document. Body. scrolltop-document. Body. clienttop
};
}
You must first declare an evnet object. whenever you move the mouse, click, or press a button, it will correspond to an event. in Internet Explorer, event is a global variable and will be stored in window. event. in Firefox, or in other browsers, Event Events are obtained by corresponding user-defined functions. when we assign the mousemove function to document. onmousemove, mousemove will get the mouse movement event.
(EV = EV | window. in this way, ev obtains the event in all browsers, and in Firefox, "| window. event does not work, because EV already has a value assignment. EV is empty in MSIE, so eV is set to window. event.
Because we need to obtain the mouse coordinates multiple times in this article, we designed the mousecoords function, which only contains one parameter, that is, the event.
We need to run in other browsers headed by MSIE and Firefox. firefox uses event. pagex and event. pagey to indicate the cursor position in the upper left corner of the document. if you have a 500*500 window and your mouse is in the middle, the paegx and Pagey will be 250. When you scroll down the Page 750 PX, The Pagey will be. pagex remains unchanged, or 250.
MSIE is opposite to this, MSIE will event. clientx and event. clienty represents the location of the mouse and IE window, not the document. when we have a 500*500 window and the mouse is in the middle, the clientx and clienty are also 250. If you scroll vertically to any position, the clienty is still 250, because the relative ie window is not changed. to get the correct result, we must add the scrollleft and scrolltop attributes relative to the mouse position of the document. finally, because MSIE does not have a starting position of 0, 0, because the 2px border is usually set, and the Border width is included in the document. body. the clientleft and clienttop attributes are added to the cursor position.
Fortunately, the mousecoords function is complete and we don't worry about coordinates anymore.
Capture mouse clicks
Next time, we will know when to click and when to release the mouse. if we skip this step, we will never be aware of the action when moving the mouse over it during drag and drop, which will be annoying and intuitive.
There are two functions to help us: onmousedown and onmouseup. we pre-set the function to receive the document. onmousemove, which looks like we will get the document. onmousedown and document. onmouseup. but when we get document. when onmousedown, we also obtain the click attributes of any object, such as text, images, and tables. we only want to get the properties that need to be dragged, so we set the function to get the objects we need to move.
Move an element
We know how to capture the mouse movement and click. the rest is the moving element. first, you need to determine a specific page location. The CSS style sheet should use 'absolute '. setting the absolute position of an element means that we can use the style sheet. top and. left to locate, you can use the relative position to locate. we move the mouse all relative to the top-left of the page. Based on this, we can proceed to the next step.
When we define item. style. Position = 'absolute ', all operations change the left and top coordinates, and then it moves.
Document. onmousemove = mousemove;
Document. onmouseup = mouseup;
VaR dragobject = NULL;
VaR mouseoffset = NULL;
Function getmouseoffset (target, Ev ){
Ev = EV | window. event;
VaR docpos = getposition (target );
VaR mousepos = mousecoords (EV );
Return {X: mousepos. X-docpos. X, Y: mousepos. Y-docpos. y };
}
Function getposition (e ){
VaR left = 0;
VaR Top = 0;
While (E. offsetparent ){
Left + = E. offsetleft;
Top + = E. offsettop;
E = E. offsetparent;
}
Left + = E. offsetleft;
Top + = E. offsettop;
Return {X: Left, Y: Top };
}
Function mousemove (EV ){
Ev = EV | window. event;
VaR mousepos = mousecoords (EV );
If (dragobject ){
Dragobject. style. Position = 'absolute ';
Dragobject. style. Top = mousepos. Y-mouseoffset. Y;
Dragobject. style. Left = mousepos. X-mouseoffset. X;
Return false;
}
}
Function mouseup (){
Dragobject = NULL;
}
Function makedraggable (item ){
If (! ITEM) return;
Item. onmousedown = function (EV ){
Dragobject = this;
Mouseoffset = getmouseoffset (this, Ev );
Return false;
}
}
You will notice thisCodeAlmost the complete set above, combining the previous one achieves the drag-and-drop effect.
When we click an item, we get a lot of variables, such as the mouse position. The mouse position naturally contains the coordinate information of the item. if we click the center of a 20*20 PX image, the relative coordinates of the mouse are {X: 10, Y: 10 }. when we click the upper left corner of the image, the relative coordinates of the mouse are {X: 0, Y: 0 }. when we click, we use this method to obtain information about Mouse and image verification. if the page item cannot be loaded, the information will be the document information, and the clicked item information will be ignored.
The mouseoffset function uses another function, getposition. getposition is used to return the coordinates of the item in the upper left corner of the page. offsetleft or item. style. left, then we will get the position of the item relative to the parent level, not the entire document. all scripts are relative to the entire document, which is better.
To complete the getposition task, you must cyclically obtain the parent level of the item. We will load the content to the position on the Left/top of the item. We need to manage the desired top and left lists.
Since the mousemove function is defined, mousemove will continue to run. first, determine the style of the item. position is absolute. Second, we move the item to the position defined above. when mouse clicks are released and dragobject is set to null, mousemove will not do anything.
Dropping an item
The purpose of the preceding example is to drag the item to the desired place. we often have other purposes, such as deleting items. For example, we can drag items into a waste bin or place defined on other pages.
Unfortunately, we have a big problem. When we drag, the item will be under the mouse, such as mouseove, mousedown, mouseup or other mouse actions. if we drag an item to the recycle bin, the mouse information is still on the item, not on the recycle bin.
How can this problem be solved? There are several ways to solve this problem. first, this is previously recommended. When we move the mouse, the item will follow the mouse and take over mouse events such as Mouseover/mousemove. We will not do this, but let the item follow the mouse, it does not occupy mouse events such as Mouseover. This will solve the problem, but it is not nice. We still hope that the item can be directly under the mouse.
Another option is not to drag items. You can change the mouse pointer to display the items to be dragged and place them in the place where the mouse is released. This solution is unacceptable for aesthetic reasons.
The final solution is that we do not remove the drag effect. this method is much more complicated than the first two methods. We need to define the list of targets to be released. When the mouse is released, manually check whether the released position is in the target list, it indicates the target location is released.
/*
All code from the previous example is needed with the exception
Of the mouseup function which is replaced below
*/
VaR droptargets = [];
Function adddroptarget (droptarget ){
Droptargets. Push (droptarget );
}
Function mouseup (EV ){
Ev = EV | window. event;
VaR mousepos = mousecoords (EV );
For (VAR I = 0; I <droptargets. length; I ++ ){
VaR curtarget = droptargets [I];
VaR targpos = getposition (curtarget );
VaR targwidth = parseint (curtarget. offsetwidth );
VaR targheight = parseint (curtarget. offsetheight );
If (
(Mousepos. x> targpos. X )&&
(Mousepos. x <(targpos. x + targwidth ))&&
(Mousepos. Y> targpos. Y )&&
(Mousepos. Y <(targpos. Y + targheight ))){
// Dragobject was dropped onto curtarget!
}
}
Dragobject = NULL;
}
When the mouse is released, it determines whether the drop attribute exists. If the mouse pointer exists within the drop range, the drop operation is executed. we check whether the cursor position is in the target range (mousepos. x> targetpos. x), and the condition (mousepos. x <(targpos. X + targwidth )). if all the conditions match, the pointer is indeed within the range, and the drop command can be executed.
Pulling it all together
Finally, we have all the drag/drop script fragments! The next thing is that we will create a DOM processing. If you are not familiar with it, please read my JavaScript primer on Dom manipulation first.
The following code creates a container and converts any item that requires drag/drop to an item of a container. the code is next to the second demo in this article. You can record a list as a navigation window on the left or right, or more functions.
In the next step, we will use "fake code" to let reader see the real code. The following is a recommendation:
1. When document is loaded for the first time, create draghelper Div. draghelper adds a shadow to the moved item. the real item is not dragged, but insertbefor and appendchild are used to move it. We have hidden draghelper.
2. With the mousedown and mouseup functions, all operations will correspond to the imousedown status. imousedown is true only when the left mouse button is pressed. Otherwise, it is false.
3. We created the global variable dragdrops and the global function createdragcontainer. dragdrops contains a series of relative containers. any parameter (containers) will be reorganized and serialized through createdcragcontainer, so that it can be freely moved. the createdragcontainer function also binds items and sets attributes.
4. Now our code knows how to add each item. When we move mousemove, The mousemove function first sets the variable target and moves the cursor over the item, if this item is in the container (checked with getattribute ):
Run a short piece of code to change the target style.
Check whether the mouse is open. If not
Set curtarget to represent the current item
Record the current position of the item. If necessary, we can return it
Clone the current item to draghelper. We can move the item with shadow effect.
After the item is copied to draghelper, the original item is still under the mouse pointer. We must delete dragobj, so that the script works and dragobj is included in a container.
Capture the current coordinates, height, and width of all items in the container, so that only one record is required. when the item is drag, every time it moves with the mouse, thousands of records are recorded every shift.
If no, you do not need to do anything, because this is not an item that needs to be moved.
5. Check curtarget. It should contain a moved item. If so, perform the following operations:
Start to move the shadow item, which is created in the previous article.
Check whether the container in each current container has been moved to these ranges.
Check to see which container the dragged item belongs.
Place the item before an item in a iner, or confirm that the item is visible after the entire container.
If the cursor is not in the iner, make sure that the item is invisible.
6. The rest is to capture the mouseup event.