JavaScript implements drag-and-drop effect _javascript skills

Source: Internet
Author: User

The example of this article for everyone to share is a drag-and-drop effect, reference code, refactoring the following to understand learning.

First look at the effect:

Drag Div


Drag-and-drop status: Not Started

"Program description"

Drag principle: In fact, is in the drag block listening to the MouseDown event, the mouse clicks, through the event object to obtain the corresponding coordinate parameters. Then, when the mouse moves, listen for the MouseMove event on the document, get the mouse clientx and clienty coordinates, and then set the left and top of the drag block.

First, listen for MouseDown events.

Copy Code code as follows:
Eventutil.addeventhandler (this. Drag, "MouseDown", Bindaseventlistener (this, this. Start));

Then add the MouseMove and MouseUp events on the start

Monitor MouseMove and MouseUp events
Eventutil.addeventhandler (document, "MouseMove", this._fm);
Eventutil.addeventhandler (document, "MouseUp", THIS._FS);

When you move the mouse, set the left and top properties of the drag block:

if (!this. Lockx) this. Drag.style.left = ILeft + "px";
 if (!this. Locky) this. Drag.style.top = itop + "px"; 

Horizontal and vertical locking: You can restrict the top and left properties for the Lockx and Locky properties by judging them.

Scope Limit Locking: Sets the maximum left and top values by calculating the width of the container and the width-height difference of the drag block, to limit the left value of the drag block and the highest value to a certain range.

Full Demo:

<! DOCTYPE html>  

The above is JavaScript implementation of drag-and-drop effect of the code, I hope to help you learn.

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.