Example of javascript Implementation of simple mouse drag effect, javascript drag

Source: Internet
Author: User

Example of javascript Implementation of simple mouse drag effect, javascript drag

This article describes how javascript achieves simple mouse dragging. Share it with you for your reference. The specific analysis is as follows:

It is common to drag an element to any position on a webpage. For example, you can drag the part of a blog template to the corresponding position by yourself.

Next, we will write a simple example to achieve the effect of dragging the mouse.

When the mouse is pressed, the difference between the current position of the mouse and the left distance of the element is recorded.
When the mouse moves, assign a value to the position of the element, that is, the position of the mouse, minus the difference.
When the mouse is opened, assign null values to the mouse movement and mouse release, so that they do not have any action.

Key Aspect 1:

disx = oevent.clientX - box.offsetLeft;

Make sure that the cursor points at the element position when dragging, that is, the distance between the mouse position and the left of the element.

Key Aspect 2:

box.style.left = oevent.clientX - disx + "px";

The position of the element when dragging. The current position of the mouse minus the previously calculated value.

Okay. The Code is as follows:

<! DOCTYPE html> 

Then, there is no limit on the range of the above mouse drag, and sometimes it will be invisible outside the window. The following limits the scope.

Key Aspect 1: If the left position of an element is less than 0, assign a value of 0 to it. If the value is greater than the window size and the width of the element, assign a value to the difference between the window size and the element width.

Var boxl = oevent. clientX-disx; if (boxl <0) {boxl = 0;} else if (boxl> vieww-box. offsetWidth) {boxl = vieww-box. offsetWidth ;}<! DOCTYPE html> 

I hope this article will help you design javascript programs.

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.