Javascript Implementation of drag-and-drop effect _ javascript tips-js tutorial

Source: Internet
Author: User
This article mainly introduces information about how javascript achieves drag-and-drop effects. If you need it, you can refer to the example in this article to share with you a drag-and-drop effect. Refer to the Code to refactor the following, understanding and learning.

First, let's take a lookEffect:

Drag p


Drag and Drop status: not started

[Program description]

Drag principle: in fact, listening to the mousedown event on the drag block, When you click the mouse, get the corresponding coordinate parameters through the event object. Then, when the mouse moves, it listens to the mousemove event on the document, obtains the clientX and clientY coordinates of the mouse, and sets the left and top of the drag block.

First, listen to the mousedown event

The Code is as follows:

EventUtil. addEventHandler (this. Drag, "mousedown", BindAsEventListener (this, this. Start ));


Then add the mousemove and mouseup events on Start.

// Listen to the events EventUtil. addEventHandler (document, "mousemove", this. _ fM); EventUtil. addEventHandler (document, "mouseup", this. _ fS );

When the mouse moves, set the left and top attributes 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 determine the top and left attributes by determining the LockX and lockY attributes.

Range Limit lock: You can set the maximum left value and top value by calculating the difference between the width and the height of the drag block, to restrict the left and top values of the drag block to a certain range.

Complete DEMO:

 
  JavaScript drag-and-drop effect  

Drag p


Drag and Drop status: not started
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.