JavaScript drag and drop effect

Source: Internet
Author: User

I've been reading JavaScript books lately, and some things seem to be understandable in books, but in real hands, there are some details you don't understand. So it seems that even a simple effect, it is not easy to write, even if it is simple to write, the code is not necessarily standard, maintainability and so on. Helpless, has been learning programming has been above his business, resulting in anything can not be written out. When you don't have enough skills to write good code, learning Daniel's code is always an efficient way. Below is a drag-and-drop effect, reference code, refactoring below, to understand learning.

First look at the effect:

Drag Div


Drag-and-drop status: not started

"Program description"

Drag principle : Actually is in the drag block listens the MouseDown event, when the mouse clicks, obtains the corresponding coordinate parameter through the event object. Then, when the mouse moves, it listens to the MouseMove event on the document, gets the clientx and clienty coordinates of the mouse, and then sets the left and top of the dragged block.

First, listen to the MouseDown event.

Then add the MouseMove and MouseUp events on start

Monitor MouseMove and MouseUp event Eventutil.addeventhandler (document, "MouseMove", THIS._FM); Eventutil.addeventhandler (document, "MouseUp", THIS._FS);

When the mouse moves, 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 : Limit the top and left properties for the Lockx and Locky properties by judging them.

Range Limit Lock: limits the left and top values of a dragged block to a certain extent by calculating the width height of the container and dragging the width and height difference values of the block to set the maximum left and top values.

Full Demo:

<! DOCTYPE html>

  

JavaScript drag and drop effect

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.