JavaScript CSS Modify Learning Sixth Chapter Drag _ Basics

Source: Internet
Author: User

This element can be dragged through the arrow keys when the # link on the example box is active (either by using the TAB key and clicking Enter or by using the mouse). Then click Enter or ESC to release. (You can change these keys at will.) I'm not sure what the release key should be set to be, so enter and ESC are OK.

Use

1, copy the DragDrop object after the article.

2, copy my addeventsimple and Removeeventsimple functions, here is required.

3, set keyhtml and Keyspeed attributes (explained below).

4, make sure you want to drag the elements have location attributes: absolute or fixed.

5. Send all the elements that can be dragged to the Initelement function of the object. You can send a string of objects or object IDs. For example:

Dragdrop.initelement (' Test ');
Dragdrop.initelement (document.getElementById (' test2 '));

6, when the element is dragged, the code will automatically add dragged class. You can add some CSS effects.

7. If you want to do something after the user releases the element, you can add your own function to releaseelement.

Property

You need to set two properties.

Keyhtml contains the contents of a link that the keyboard of the element that needs to be dragged can be accessed. To keep the HTML simple, just add a class with a simple style. You can build your HTML at will, but remember that there must be a link for the keyboard to access, and the keyboard user needs a focus to trigger the drag-and-drop event.

Keyspeed is used to set the speed at which the keyboard is dragged, and how many pixels to move each key. I like to set it to 10, and you can also try other values.

There are 7 more attributes, but they are all inside the code. The initialization is set to undefined, and then the corresponding function sets them.

Drag objects




Copy the following object to your page, and don't forget Addeventsimple and removeeventsimple.

Copy Code code as follows:



DragDrop = {


keyhtml: ' <a href= ' # "class=" Keylink ">#</a>",


Keyspeed:10,//pixels per KeyPress Event


Initialmousex:undefined,


Initialmousey:undefined,


Startx:undefined,


Starty:undefined,


Dxkeys:undefined,


Dykeys:undefined,


Draggedobject:undefined,


Initelement:function (Element) {


if (typeof element = = ' String ')


element = document.getElementById (element);


Element.onmousedown = Dragdrop.startdragmouse;


element.innerhtml + = dragdrop.keyhtml;


var links = element.getelementsbytagname (' a ');


var lastlink = links[links.length-1];


Lastlink.relatedelement = element;


Lastlink.onclick = Dragdrop.startdragkeys;


},


Startdragmouse:function (e) {


Dragdrop.startdrag (this);


var evt = e | | window.event;


Dragdrop.initialmousex = Evt.clientx;


Dragdrop.initialmousey = Evt.clienty;


Addeventsimple (document, ' MouseMove ', dragdrop.dragmouse);


Addeventsimple (document, ' MouseUp ', dragdrop.releaseelement);


return false;


},


Startdragkeys:function () {


Dragdrop.startdrag (this.relatedelement);


Dragdrop.dxkeys = Dragdrop.dykeys = 0;


Addeventsimple (document, ' KeyDown ', Dragdrop.dragkeys);


Addeventsimple (document, ' KeyPress ', dragdrop.switchkeyevents);


This.blur ();


return false;


},


Startdrag:function (obj) {


if (Dragdrop.draggedobject)


Dragdrop.releaseelement ();


Dragdrop.startx = Obj.offsetleft;


Dragdrop.starty = Obj.offsettop;


Dragdrop.draggedobject = obj;


Obj.classname + = ' dragged ';


},


Dragmouse:function (e) {


var evt = e | | window.event;


var DX = Evt.clientx-dragdrop.initialmousex;


var DY = Evt.clienty-dragdrop.initialmousey;


Dragdrop.setposition (Dx,dy);


return false;


},


Dragkeys:function (e) {


var evt = e | | window.event;


var key = Evt.keycode;


Switch (key) {


Case for://Left


Case 63234:


Dragdrop.dxkeys-= Dragdrop.keyspeed;


Break


Case://Up


Case 63232:


Dragdrop.dykeys-= Dragdrop.keyspeed;


Break


Case A:/Right


Case 63235:


Dragdrop.dxkeys + = Dragdrop.keyspeed;


Break


Case://Down


Case 63233:


Dragdrop.dykeys + = Dragdrop.keyspeed;


Break


Case://Enter


Case://Escape


Dragdrop.releaseelement ();


return false;


Default


return true;


}


Dragdrop.setposition (Dragdrop.dxkeys,dragdrop.dykeys);


if (Evt.preventdefault)


Evt.preventdefault ();


return false;


},


Setposition:function (Dx,dy) {


DragDrop.draggedObject.style.left = dragdrop.startx + dx + ' px ';


DragDrop.draggedObject.style.top = dragdrop.starty + dy + ' px ';


},


Switchkeyevents:function () {


For Opera and Safari 1.3


Removeeventsimple (document, ' KeyDown ', Dragdrop.dragkeys);


Removeeventsimple (document, ' KeyPress ', dragdrop.switchkeyevents);


Addeventsimple (document, ' KeyPress ', Dragdrop.dragkeys);


},


Releaseelement:function () {


Removeeventsimple (document, ' MouseMove ', dragdrop.dragmouse);


Removeeventsimple (document, ' MouseUp ', dragdrop.releaseelement);


Removeeventsimple (document, ' KeyPress ', Dragdrop.dragkeys);


Removeeventsimple (document, ' KeyPress ', dragdrop.switchkeyevents);


Removeeventsimple (document, ' KeyDown ', Dragdrop.dragkeys);


DragDrop.draggedObject.className = DragDrop.draggedObject.className.replace (/dragged/, ");


Dragdrop.draggedobject = null;


}


}





What's the drag?


Drag is a way to move elements on the screen. In order for the element to move, the element must have a position attribute: absolute or fixed, so that it can be moved by modifying its coordinates (STYLE.TOP and style.left).


(theoretically position:relative can be, but it's almost useless.) In addition, that requires additional data to compute, I do not write here.


Setting the coordinates is simple; finding the coordinates of the elements you need to set is a difficult part of the code. Most of the code is used to deal with this problem.


In addition, it is important to maintain ease of use. Traditionally, it is best to drag and drop an element with the mouse, but it is also useful to keep the keyboard available, taking into account the user without the mouse.





Basic knowledge


Let's take a look at some basic knowledge first


Initialize an element


Each drag-and-drop code starts with the initialization element. This work is done through the following letter:


Copy Code code as follows:

Initelement:function (Element) {
if (typeof element = = ' String ')
element = document.getElementById (element);
Element.onmousedown = Dragdrop.startdragmouse;
element.innerhtml + = dragdrop.keyhtml;
var links = element.getelementsbytagname (' a ');
var lastlink = links[links.length-1];
Lastlink.relatedelement = element;
Lastlink.onclick = Dragdrop.startdragkeys;
},



If a function receives a string, it is treated as an element ID. Then set a onmousedown event for this element to start the mouse part of the code. Note that I am using the traditional event registration method, because I want the this keyword to work in Startdragdrop.





Then add the user-defined keyhtml to the element, which I believe is used to trigger keyboard events. Then set the keyboard trigger for this link. Then store the main element inside the relatedelement and we need it later.





Now the code is waiting for the user to move.





Basic location information


I'm going to use the following method: First I'll read the initial position of the drag element and save it in StartX and Starty. It then calculates the position of the mouse movement or the position under the keyboard control to determine the range from which the element moves from its original position.





StartX and Starty are set by the StartDrag function, which is used in both mouse and keyboard events.


Copy Code code as follows:

Startdrag:function (obj) {
if (Dragdrop.draggedobject)
Dragdrop.releaseelement ();
Dragdrop.startx = Obj.offsetleft;
Dragdrop.starty = Obj.offsettop;
Dragdrop.draggedobject = obj;
Obj.classname + = ' dragged ';
},



First, if the element is in a drag state, then we release him (we'll talk later).


The function then finds the coordinates of the element at the starting position (Offsetleft and offsettop), and then saves the StartX and Starty for later use.


Then, in Draggedobject, you save a reference to an object. Then add the dragged class to him, so you can set the drag-and-drop style with CSS.


When a user uses a mouse or a keyboard to drag and drop elements, the most complex part of the code tracks the change in position. Then give the DX and dy (x and y changes). And then adding StartX and Starty is where the element is now.


The following function is used to set the location:


Copy Code code as follows:

Setposition:function (Dx,dy) {
DragDrop.draggedObject.style.left = dragdrop.startx + dx + ' px ';
DragDrop.draggedObject.style.top = dragdrop.starty + dy + ' px ';
},



The function uses the mouse and keyboard movements to compute the DX and dy with the initial position to set the new position of the element.


This part is very simple, the complex place lies in DX and Dy's obtains, the mouse part and the keyboard part processing is very different, we look separately.





Mouse part of the code


The part of the mouse is more complex to compute than the keyboard, but there is little problem with browser compatibility. So we start with the mouse section.


Event


First we'll discuss the event. Obviously, the drag and drop process requires Mousedown,mousemove,mouseup to complete the selection of objects, drag and drop to complete these actions.


This series of events starts with a MouseDown event that needs to drag and drop elements. So all drag-and-drop elements need this event to mark the start of the drag. We see:


Copy Code code as follows:
Element.onmousedown = Dragdrop.startdragmouse;



However, the MouseMove and MouseUp events should not be set on the elements but should be set on the entire document. Because the user can quickly and crazily move the mouse, and then lose the drag element. If set on an element, it may be out of control because the mouse is not on the element, which is not good for ease of use.


If we set up MouseMove and MouseUp on the document, there is no such problem. Regardless of where the mouse is, the elements respond to both MouseMove and MouseUp. The ease of use is strong.


In addition, you can only set MouseMove and MouseUp after dragging and dropping, and then delete them after the user frees the elements. This code is clean and saves system resources because the MouseMove consumes a lot of the system.


Mousedown


When the drag element occurs MouseDown event, the Startdragmouse function starts executing:


First we will execute the StartDrag we discussed earlier. Then locate the coordinates of the mouse and save them in Initialmousex and Initialmousey. We'll compare the mouse position to this.

Finally returns false, which is used to block the default mouse event: Select text. It's annoying when we don't want the text to be picked up when we're dragging.

Then set up the MouseUp and MouseMove event handlers for the document. Because it is possible that the document has his own MouseUp and MouseMove event handlers, I use my addeventsimple function to prevent the original event handlers from being invalidated.
Mousemove
Now, the Dragmouse function executes when the user moves the mouse.

Copy Code code as follows:

Dragmouse:function (e) {
var evt = e | | window.event;
var DX = Evt.clientx-dragdrop.initialmousex;
var DY = Evt.clienty-dragdrop.initialmousey;
Dragdrop.setposition (Dx,dy);
return false;
},



This function reads the current coordinates of the mouse, subtracts the previous coordinates, and passes the resulting dx and dy to the seposition.

It then prevents the mouse from selecting the default property of the text by returning false.

Mouseup

When the user releases the mouse, the releaseelement is invoked. We'll talk about it later.

Keyboard part Code

Now let's start with a more complex keyboard section of code. Unlike the mouse drag and drop, keyboard drag and drop does not have a standard. Although the basic interaction is not too complicated, it is best to give a brief explanation.

Basic interaction

The key used to drag is the arrow key, which is very simple.

Activating and releasing elements is tricky, and my code needs to be enhanced here.

I think if you use the keyboard to activate, you should use an additional link that I added. There's not much to choose from: The link gets the focus in all browsers (okay, the form is OK, you are the checkbox, and it is logical to place a link inside a drag element (you can put it anywhere, but how do you let the user know that it is used to activate drag-and-drop?) )。

I assume that when the user clicks on Enter or ESC to release the element, at least I don't find any other appropriate keys. If you want to choose something else, you can find the keyboard code here.

Case://Enter
Case://Escape
Dragdrop.releaseelement ();
return false;

Event

Click to activate the element. Click the ENTER key when the mouse clicks on the link or when the element gets focus. So the activation of the keyboard code allows you to click the ENTER key or click the link.

(Strictly speaking, when you click the link with the mouse, the element is activated by the mouse event first and then released and then activated by keyboard mode.) )

The rest of the event is also very vague. Keyboard events are especially troublesome when you want to detect the arrow keys.

First we need an event that allows repeated clicks, because the user may press the direction key, then the event needs to be triggered over and over, so that the drag can continue. So we use the KeyPress event.

Unfortunately, IE does not support directional keys in the case of KeyPress. In IE KeyDown will recur, it seems that we need to use the KeyDown event.

You may not be able to get things that simple. In opera and Safari, the KeyDown event can only be triggered once, so when the user presses the key, the element moves once and then does not move. We need keypress in these browsers.

So ideally, we use keypress, if not supported, is to use KeyDown. But how do you switch events? How do you know keypress can't be used at this time?

My solution is to set an event handler for the KeyPress event. If the program executes the instructions to support KeyPress, we can switch safely.

The Startdragkeys function is used to set the KeyDown and KeyPress events:

Copy Code code as follows:

Addeventsimple (document, ' KeyDown ', Dragdrop.dragkeys);
Addeventsimple (document, ' KeyPress ', dragdrop.switchkeyevents);



First, the KeyDown trigger completes the drag-and-drop dragkeys function. This is the first event that is triggered, and the element always moves. Then we do other things, then the elements in opera and Safari1.3 after moving one time will stop.


That's why we still need keypress. The first KeyPress event triggers the switchkeyevents function, which adjusts the event handler:


Copy Code code as follows:

Switchkeyevents:function () {
Removeeventsimple (document, ' KeyDown ', Dragdrop.dragkeys);
Removeeventsimple (document, ' KeyPress ', dragdrop.switchkeyevents);
Addeventsimple (document, ' KeyPress ', Dragdrop.dragkeys);
},



He will remove the original event handler first, then set KeyPress to trigger Dragkeys. Because this function will only execute in the browsers that support him, we will only change KeyDown to KeyPress in these browsers.


Initial keyboard code


When the user clicks on the connection to activate the element, the Startdragkeys is invoked.


Copy Code code as follows:

Startdragkeys:function () {
Dragdrop.startdrag (this.relatedelement);
Dragdrop.dxkeys = Dragdrop.dykeys = 0;
Addeventsimple (document, ' KeyDown ', Dragdrop.dragkeys);
Addeventsimple (document, ' KeyPress ', dragdrop.switchkeyevents);
This.blur ();
return false;
},



We will first call the StartDrag function we discussed earlier. He will pass relatedelement to this function, which is the element to be dragged.


Then set the Dxkeys and Dykeys to 0. These variables are used to track the displacement of elements.


Then set up the event handler, which has been discussed above.


Then remove the focus of the link you just clicked. I do this because the ENTER key frees the element, but if the focus is not removed, the element is released when the user clicks on the ENTER key, but the link is then clicked again, and it becomes a drag mode. If we remove the focus, then the problem does not exist.


Finally returns false to block the default action.


dragging through the keyboard


Dragkeys is responsible for the keyboard drag and drop:


Copy Code code as follows:

Dragkeys:function (e) {
var evt = e | | window.event;
var key = Evt.keycode;



We first read the key value of the keyboard.


Then we use the switch statement to determine what we do. The purpose of this section is to update the values of Dxkeys and Dykeys, and you can move elements by setting the position of the element.


Copy Code code as follows:



Switch (key) {


Case for://Left


Case 63234:


Dragdrop.dxkeys-= Dragdrop.keyspeed;


Break


Case://Up


Case 63232:


Dragdrop.dykeys-= Dragdrop.keyspeed;


Break


Case A:/Right


Case 63235:


Dragdrop.dxkeys + = Dragdrop.keyspeed;


Break


Case://Down


Case 63233:


Dragdrop.dykeys + = Dragdrop.keyspeed;


Break





The author sets the keyspeed to determine the pixel size for each move. When the user clicks the left direction key, subtracts the keyspeed.





This code contains 63232-63235 of the cases. Because Safari1.3 does not use the key value of the standard 37-40 arrow keys (Safari 3 already supports it).





Copy Code code as follows:
Case://Enter
Case://Escape
Dragdrop.releaseelement ();
return false;



If the user clicks the Enter or ESC key, the Releaseelement () function is invoked. If you want to change the button that releases the element, you can add it here.





Copy Code code as follows:
Default
return true;
}



If the user presses another key, the default action is performed and the function ends.





Copy Code code as follows:
Dragdrop.setposition (Dragdrop.dxkeys,dragdrop.dykeys);



Now Dxkeys and Dykeys have updated us to send to the SetPosition () function to change the position of the element.





Copy Code code as follows:
if (Evt.preventdefault)
Evt.preventdefault ();
return false;
},



Finally, we need to block the default event, and if the user clicks the next arrow key, the page scrolls down after the above code is executed. The Preventdefault is implemented in the Web-compatible browser by returning false in IE.








Releasing elements


When the user releases the element, the function releaseelement is invoked. He removes the event handlers for all code settings, removes the dragged class, cleans the Draggedobject, and waits for user action.


Copy Code code as follows:

Releaseelement:function () {
Removeeventsimple (document, ' MouseMove ', dragdrop.dragmouse);
Removeeventsimple (document, ' MouseUp ', dragdrop.releaseelement);
Removeeventsimple (document, ' KeyPress ', Dragdrop.dragkeys);
Removeeventsimple (document, ' KeyPress ', dragdrop.switchkeyevents);
Removeeventsimple (document, ' KeyDown ', Dragdrop.dragkeys);
DragDrop.draggedObject.className = DragDrop.draggedObject.className.replace (/dragged/, ");
Dragdrop.draggedobject = null;
}



You might want to do something after the user releases the element, and you can add your function here.


Translation Address: http://www.quirksmode.org/js/dragdrop.html


Reprint please keep the following information


Author: North Jade (TW: @rehawk)

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.