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.