Javascript separates the mouse click and drag events, and javascript drag

Source: Internet
Author: User

Javascript separates the mouse click and drag events, and javascript drag

In javascript, common DOM elements such as div all have three mouse events: onmousedown, onmousemove, and onmouseup.

<div id="div1" onmousedown="down();" onmouseup="up();" onmousemove="move();"></div>

 

The onmousemove event is triggered when you move the mouse over div1 or press the left button to drag the mouse. How can we differentiate these two events? How can I distinguish between mouse-clicked and drag-and-pull? You can register the onmousedown and onmouseup event processing functions to distinguish between the mouse and the drag. In onmousedown, you can record the position where the mouse is pressed, and in onmouseup, record the position where the mouse is played, then compare the gaps between the two positions. If the distance difference is not large, the cursor is clicked and then the cursor is clicked. If the Distance Difference is large, the cursor is dragged and then popped up. The following describes how to use setTimeout.

<Div id = "div1" onmousedown = "down ();" onmouseup = "up ();" onmousemove = "move (); "/> <script type =" text/javascript "> var timmerHandle = null; var isDrag = false; function down () {console. log ("mouse down. "); // because mouseDownFun is called every time, the isDrag variable is reinitialized here = false; // The latency is 100 ms timmerHandle = setTimeout (setDragTrue, 200 );} function setDragTrue () {isDrag = true;} function move () {// you can use isDrag to determine whether to move or drag} functi On up () {if (! IsDrag) {// clear doMouseDownTimmer first. Otherwise, the setGragTrue method will still be called clearTimeout (timmerHandle) after 200 milliseconds; console. log ("mouse up. ");} else {isDrag = false; console. log ("draging over. ") ;}}</script>

 

Using setTimeout is time-based and using coordinates is space-based.

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.