JavaScript to implement simple mouse drag effect instance _javascript skill

Source: Internet
Author: User

This article describes the JavaScript implementation of simple mouse drag effect. Share to everyone for your reference. The specific analysis is as follows:

Drag an element with the mouse, put it in any position in the Web page, this is very common, such as many blog template block position can drag themselves to the appropriate location.

The following first write a simple mouse can be dragged to achieve the effect.

When the mouse is pressed, record the difference between the current position of the mouse and the distance to the left of the element.
When the mouse is moving, the position of the element is assigned to the position of the mouse, minus just the difference.
When the mouse is open, give the mouse move and the mouse to let go of the assignment null, so that they do not have any action.

Point one:

DISX = Oevent.clientx-box.offsetleft;

To determine when you drag the mouse point at the position of the element, that is, the mouse position minus the left distance of the element.

Point two:

Box.style.left = Oevent.clientx-disx + "px";

The position of the element when dragged, and the current position of the mouse minus the previously calculated value.

Okay, on the code:

 <! DOCTYPE html>  
 

To improve, the above mouse drag does not limit the range, and sometimes drag the window out of sight. Below, limit the range.

Important one: If the left position of the element is less than 0 o'clock, assign it a value of 0, and if it is greater than the window size minus the width of the element itself, assign it the difference of the width of the window size minus the element itself.

var boxl = Oevent.clientx-disx;
  if (Boxl < 0) {Boxl = 0;
  }else if (Boxl > Vieww-box.offsetwidth) {boxl = Vieww-box.offsetwidth; } <! DOCTYPE html>  

The

wants this article to help you with your JavaScript programming.

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.