简体   繁体   English

如何在JavaScript中的同一元素上应用longclick事件和doubleclick事件

[英]How to apply long click event and doubleclick event on the same element in javascript

I have an element(textArea). 我有一个element(textArea)。 Now I would like a long press event and a double click event on the element. 现在,我想要在元素上进行长按和双击事件。 I am able to do this but I would also like to use event.preventDefault() in the mousedown event of long press event. 我能够做到这一点,但我也想在长按事件的mousedown事件中使用event.preventDefault()。 This in turn prevents the dblClick event also. 反过来,这也可以防止dblClick事件。

The reason why I want to preventDefault is I am rendering an element on longPress and wanted to prevent the initial mouseDown as I am firing mousemove after longpress. 我要阻止Default的原因是我在longPress上渲染了一个元素,并希望在longpress之后触发mousemove时阻止初始mouseDown。 I have searched and re-searched the net but am unable to find a good answer which solves the problem of long press and dblclick on the same element. 我已经搜索并重新搜索了网络,但是找不到一个很好的答案,这解决了长按和双击同一元素的问题。

thanks!! 谢谢!!

try this Demo 试试这个演示

HTML HTML

<input type="button" ondblclick="whateverFunc()" onmousedown="func(event)" onmouseup="revert()" value="hold for long"/>

JavaScript JavaScript的

var timer;
var istrue = false;
var delay = 3000; // how much long u have to hold click in MS
function func(e)
{
   istrue = true;
   timer = setTimeout(function(){ makeChange();},delay);
  // Incase if you want to prevent Default functionality on mouse down
  if (e.preventDefault) 
  { 
     e.preventDefault();
  } else {
     e.returnValue = false; 
  }
}

function makeChange()
{
      if(timer)
      clearTimeout(timer);

      if(istrue)
      {
            /// rest of your code
          alert('holding');

      }
}
function revert()
{
   istrue =false;
}
function whateverFunc()
{
    alert('dblclick');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM