Distinguish mouse click and drag events in JavaScript

Source: Internet
Author: User

In JavaScript, the general DOM elements, such as Div, have onmousedown, onmousemove, onmouseup 3 mouse events.

<div id= "Div1" onmousedown= "Down ()," onmouseup= "Up ();" Onmousemove= "Move ();" ></div>

The onmousemove event is triggered when the mouse is moved on the Div1 or when the left-click drag is pressed. How to distinguish between these 2 kinds of events? How to distinguish the mouse click Bounce up and drag after it? after the mouse click Bounce and drag, you can register the onmousedown and onmouseup event handlers, record the position of the mouse pressed in the onmousedown, OnMouseUp The position of the mouse bounce, and then compare the 2 position gaps. If the distance gap is not small, it is the mouse click on the rebound, if the distance is large, it is the mouse to play after dragging. The following describes the use of settimeout to implement.

<div id= "Div1" onmousedown= "Down ()," onmouseup= "Up ();" Onmousemove= "Move ();"/><script type= "text/ JavaScript ">    var timmerhandle = null;    var Isdrag = false;        function down ()    {    Console.log ("mouse");        Because Mousedownfun is called every time, this variable is reinitialized here        Isdrag = false;            Delay 100ms        timmerhandle = setTimeout (setdragtrue,200);    }        function Setdragtrue ()    {    Isdrag = true;    }    function Move ()    {//can use Isdrag to determine whether to move or drag    }            function up ()    {            if (!isdrag)        {        // First clear the Domousedowntimmer, or 200 milliseconds after the Setgragtrue method will be called            cleartimeout (timmerhandle);             Console.log ("Mouse up.");        }    else    {        Isdrag = false;        Console.log ("draging over.");    }    } </script>

Using settimeout This is a time-based approach, and using coordinates is a space-based approach.

Distinguish mouse click and drag events in JavaScript

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.