JavaScript CSS modification and learning Chapter 6 drag

Source: Internet
Author: User
Document directory
  • Attribute
  • Mouseup
  • Basic Interaction
  • Event

When the # link on the box in the example is in the active State (whether using a tab and then clicking enter or clicking with the mouse), this element can be dragged by the direction key. Then click enter or Esc release. (You can change these keys at will. I'm not sure what the release key should be set, so both enter and Esc can be)

Use

1. Copy the dragDrop object after the article.

2. Copy my addEventSimple and removeEventSimple functions, which are required here.

3. Set the keyHTML and keySpeed attributes (as explained below ).

4. Make sure that all the elements you want to drag have the location attribute absolute or fixed.

5. Send all the drag-and-drop elements to the initElement function of the object. A string that can send an object or an object ID. For example:

dragDrop.initElement('test');
dragDrop.initElement(document.getElementById('test2'));

6. After an element is dragged, the code automatically adds the 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 the releaseElement.

Attribute

You need to set two attributes.

KeyHTML contains the link content that can be accessed by the keyboard of an element to be dragged. To keep the HTML concise, add only one class with simple styles. You can build your HTML at will, but remember that there must be a link for the keyboard to access. The keyboard user needs a focus to trigger the drag and drop event.

KeySpeed is used to set the speed of keyboard drag and drop, and how many pixels each key moves. I like to set it to 10. You can try other values.

There are also seven attributes, but they are all in the code. It is set to undefined during initialization, and then corresponding functions will set them.

Drag objects

Copy the following object to your page. Do not forget addEventSimple and removeEventSimple.

Copy codeThe Code is 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, 'keylow', 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 + = 'draged ';
},
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 37: // left
Case 63234:
DragDrop. dXKeys-= dragDrop. keySpeed;
Break;
Case 38: // up
Case 63232:
DragDrop. dYKeys-= dragDrop. keySpeed;
Break;
Case 39: // right
Case 63235:
DragDrop. dXKeys + = dragDrop. keySpeed;
Break;
Case 40: // down
Case 63233:
DragDrop. dYKeys + = dragDrop. keySpeed;
Break;
Case 13: // enter
Case 27: // 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, 'keylow', 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, 'keylow', dragDrop. dragKeys );
DragDrop. draggedObject. className = dragDrop. draggedObject. className. replace (/dragged /,'');
DragDrop. draggedObject = null;
}
}

What is drag
Drag is a way to move elements on the screen. To make the element move, the element must have the position attribute absolute or fixed so that it can be moved by modifying its coordinates (style. top and style. left.
(In theory, position: relative is acceptable, but it is almost useless. In addition, additional data is required for calculation. I did not write it here)
It is easy to set coordinates. Finding the coordinates of the elements to be set is a difficult part of the code. Most code is used to handle this problem.
In addition, maintaining ease of use is also important. Traditionally, it is the best way to drag an element with the mouse, but users without the mouse should also be considered, so the availability of the keyboard should also be ensured.

Basic knowledge
Let's take a look at some basic knowledge.
Initialize an element
Each drag-and-drop code starts from the initialization element. This work is completed through the following letter:Copy codeThe Code is 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 processed as an element ID. Set an onmousedown event for this element to start the code of the mouse part. Note that here I use the traditional event registration method, because I want this keyword to work in startDragDrop.

Then add the User-Defined keyHTML to the element. I believe this link is used to trigger Keyboard Events. Set the keyboard trigger program for this link. The primary element is stored in the relatedElement, which we need later.

Now the code is waiting for user actions.

Basic Location Information
I plan to use the following method: first, I will read the initial position of the drag and drop elements and save them in startX and startY. Then, the moving position of the mouse or the Moving position under the control of the keyboard is calculated to determine the range of elements moving from the initial position.

StartX and startY are set using the startDrag function, which is used in mouse and keyboard events.Copy codeThe Code is as follows: startDrag: function (obj ){
If (dragDrop. draggedObject)
DragDrop. releaseElement ();
DragDrop. startX = obj. offsetLeft;
DragDrop. startY = obj. offsetTop;
DragDrop. draggedObject = obj;
Obj. className + = 'draged ';
},

First, if the element is in the drag and drop State, we will release it (we will talk about it later ).
The function then finds the coordinates of the element at the starting position (offsetLeft and offsetTop), and stores them in startX and startY for future use.
Then save an object reference in draggedObject. Then add the dragged class to him, so that you can use CSS to set the style when dragging.
When you drag an element with the mouse or keyboard, the most complex part of the code is to track the location changes. Then dX and dY (X and Y) are given ). Add startX and startY as the current position of the element.
The following function is used to set the position:Copy codeThe Code is as follows: setPosition: function (dx, dy ){
DragDrop. draggedObject. style. left = dragDrop. startX + dx + 'px ';
DragDrop. draggedObject. style. top = dragDrop. startY + dy + 'px ';
},

The function moves the mouse and keyboard to calculate the dX, dY, and initial position to set the new position of the element.
This part is very simple. The complicated part lies in the acquisition of dx and dy. The processing of the mouse part and the keyboard part is very different. Let's look at it separately.

Code of the mouse part
The calculation of the mouse part is more complicated than that of the keyboard, but the browser compatibility is not a problem. So we start with the mouse.
Event
First, let's discuss the event. Obviously, mousedown, mousemove, and mouseup are required during the drag and drop process to complete the selection, drag, and drag operations.
This series of events starts with the mousedown event that requires dragging elements. Therefore, this event is required for all drag elements to indicate that the drag starts. We can see:Copy codeThe Code is as follows: element. onmousedown = dragDrop. startDragMouse;

However, the mousemove and mouseup events should not be set on the element but on the entire document. Because the user may quickly move the mouse wildly and then lose the drag element. If it is set on an element, it may be uncontrollable because the mouse is not on the element, which is not a good thing for ease of use.
If we set mousemove and mouseup in the document, there is no such problem. No matter where the mouse is located, the element will respond to mousemove and mouseup. This is easy to use.
In addition, you can only set mousemove and mouseup after the drag and drop, and then delete the elements after the user releases them. In this way, the code is very clean and saves system resources, because mousemove consumes a lot of resources.
Mousedown
When a mousedown event occurs on the drag and drop elements, the startDragMouse function starts to execute:

The startDrag we discussed earlier will be executed first. Search for the mouse coordinates and save them in initialMouseX and initialMouseY. Next we will compare the mouse position with this.

Finally, false is returned, which is used to prevent the default mouse event: select text. We don't want to drag or drop any text to be selected, which is annoying.

Set the mouseup and mousemove Event Handlers for the document. Because the document may have its own mouseup and mousemove event handlers, I use my addEventSimple function to prevent the original event handler from being invalid.
Mousemove
Now, when the user moves the mouse, the dragMouse function is executed.

Copy codeThe Code is 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 will read the current coordinates of the mouse, then subtract the previous coordinates, and pass the obtained dX and dY to the sePosition.

Then, false is returned to prevent the mouse from selecting the default attribute of the text.

Mouseup

When you release the mouse, the releaseElement is called. We will discuss it later.

Keyboard code

Now let's start some more complex keyboard code. Unlike dragging a mouse, dragging a keyboard is not a standard. Although the basic interaction is not too complex, it is best to briefly describe it.

Basic Interaction

The keys used for dragging are preferably direction keys, which is very simple.

Activating and releasing elements are more skillful. Here, my code needs to be enhanced.

I think if I use a keyboard for activation, I should use an additional link I added. There is not much choice here: Because the link can get the focus in all browsers (well, the form can also be, you can also select the check box ), it is also logical to place a link in a drag-and-drop element (you can place it anywhere, but how can you let users know that it is used to activate drag-and-drop ?).

I assume that when you click enter or Esc to release the element, at least I have not found any other suitable key. If you want to select others, you can find the keyboard code here.

case 13: // enter
case 27: // escape
dragDrop.releaseElement();
return false;

Event

Click to activate the element. When you click the link or when the element gets the focus, click enter to activate it. Therefore, to activate the keyboard code, click enter or click the link.

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

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

First, we need an event that allows repeated clicks, because the user may press the direction key to not place it, then the event needs to be triggered over and over again, so that the drag and drop operation can continue. So we use the keypress event.

Unfortunately, IE does not support direction keys in the case of keypress. Keydown will occur again in IE. It seems that we need to use the keydown event.

It's not that easy for you. In Opera and Safari, The keydown event can only be triggered once, so when the user presses the key, the element will not move once. Keypress is required in these browsers.

Therefore, in ideal cases, keypress is used. If keydown is not supported, keydown is used. But how to switch events? How do you know that keypress cannot be used at this time?

My solution is to set an event handler for the keypress event. If this program is executed, keypress is supported, and we can switch it over safely.

The startDragKeys function is used to set keydown and keypress events:

Copy codeThe Code is as follows: addEventSimple (document, 'keylow', dragDrop. dragKeys );
AddEventSimple (document, 'keypress', dragDrop. switchKeyEvents );

First, the keydown trigger completes the dragKeys function of the drag and drop operation. This is the first trigger event, and the elements will always move. If we do other things, the elements will be moved once in Opera and Safari1.3 and will be stopped.
That's why we still need keypress. The first keypress event triggers the switchKeyEvents function, which adjusts the event handler:Copy codeThe Code is as follows: switchKeyEvents: function (){
RemoveEventSimple (document, 'keylow', dragDrop. dragKeys );
RemoveEventSimple (document, 'keypress', dragDrop. switchKeyEvents );
AddEventSimple (document, 'keypress', dragDrop. dragKeys );
},

He will first Delete the original event handler, and then set keypress to trigger dragKeys. Because this function will only be executed in browsers that support it, we only change keydown to keypress in these browsers.
Initial keyboard code
When a user clicks a connection to activate the element, the user calls startDragKeys.Copy codeThe Code is as follows: startDragKeys: function (){
DragDrop. startDrag (this. relatedElement );
DragDrop. dXKeys = dragDrop. dYKeys = 0;
AddEventSimple (document, 'keylow', dragDrop. dragKeys );
AddEventSimple (document, 'keypress', dragDrop. switchKeyEvents );
This. blur ();
Return false;
},

The startDrag function we discussed earlier will be called first. It will pass the relatedElement to this function, that is, the element to be dragged.
Set dXKeys and dYKeys to 0. These variables are used to track the displacement of elements.
Set the event handler as discussed above.
Remove the focus of the link you just clicked. This is because the Enter key releases the element, but if the focus is not removed, the element is released after the user clicks the Enter key, but the link is again clicked by the Enter key, it becomes a drag-and-drop mode. If we remove the focus, the problem does not exist.
Finally, false is returned to stop the default action.
Drag through the keyboard
DragKeys is responsible for keyboard dragging:Copy codeThe Code is as follows: dragKeys: function (e ){
Var evt = e | window. event;
Var key = evt. keyCode;

First, read the key value of the keyboard.
Then we use the switch statement to determine how to do it. This part aims to update the values of dXKeys and dYKeys so that you can move the elements by setting their positions.Copy codeThe Code is as follows: switch (key ){
Case 37: // left
Case 63234:
DragDrop. dXKeys-= dragDrop. keySpeed;
Break;
Case 38: // up
Case 63232:
DragDrop. dYKeys-= dragDrop. keySpeed;
Break;
Case 39: // right
Case 63235:
DragDrop. dXKeys + = dragDrop. keySpeed;
Break;
Case 40: // down
Case 63233:
DragDrop. dYKeys + = dragDrop. keySpeed;
Break;

The author sets keySpeed to determine the size of each moving pixel. When the user clicks the left arrow key, the keySpeed is subtracted.

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

Copy codeThe Code is as follows: case 13: // enter
Case 27: // escape
DragDrop. releaseElement ();
Return false;

If you click Enter or Esc, call the releaseElement () function. If you want to change the button of the release element, you can add it here.

Copy codeThe Code is as follows: default:
Return true;
}

If you press another key, the default action is executed and the function is ended.

Copy codeThe Code is as follows: dragDrop. setPosition (dragDrop. dXKeys, dragDrop. dYKeys );

Now dXKeys and dYKeys have updated the positions of elements we sent to the setPosition () function.

Copy codeThe Code is as follows: if (evt. preventDefault)
Evt. preventDefault ();
Return false;
},

Finally, we need to block the default event. If you click the arrow key, the page will scroll down after the above code is executed. In W3C compatible browsers, preventDefault is implemented, and false is returned in IE.

Release Element
When an element is released, the function releaseElement is called. It will remove all the Event Handlers set in the code, remove the dragged class, clear the draggedObject, and wait for the user action.Copy codeThe Code is 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, 'keylow', dragDrop. dragKeys );
DragDrop. draggedObject. className = dragDrop. draggedObject. className. replace (/dragged /,'');
DragDrop. draggedObject = null;
}

You may want to do something after the user releases the element. You can add your function here.
Http://www.quirksmode.org/js/dragdrop.html
Reprinted please keep the following information
Author: Beiyu (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.