如何在JavaScript中的同一个元素上应用长时间点击事件和doubleclick事件 [英] How to apply long click event and doubleclick event on the same element in javascript

查看:129
本文介绍了如何在JavaScript中的同一个元素上应用长时间点击事件和doubleclick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个元素(textArea)。现在我想要一个长按事件和一个双击事件的元素。我可以这样做,但我也想在长按事件的mousedown事件中使用event.preventDefault()。这反过来也会阻止dblClick事件。



为什么我想要防止缺省的原因是我在longPress上渲染一个元素,并希望防止在我长时间发射mousemove之后的最初的mouseDown。我已经搜索并重新搜索了网络,但无法找到一个很好的答案,解决了同一个元素上的长按和dblclick问题。



谢谢!!

解决方案

尝试这个 演示



HTML

 < input type =buttonondblclick =whateverFunc()onm​​ousedown =func(event)onm​​ouseup =revert()value =hold for long/> 

JavaScript

  var timer; 
var istrue = false;
var delay = 3000; //你需要多长时间持有MS
函数func(e)
{
istrue = true;
timer = setTimeout(function(){makeChange();},delay);
//如果你想防止鼠标下的默认功能
if(e.preventDefault)
{
e.preventDefault();
} else {
e.returnValue = false;
}
}

函数makeChange()
{
if(timer)
clearTimeout(timer);

if(istrue)
{
///其他代码
alert('holding');

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


I have an 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. This in turn prevents the dblClick event also.

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. 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

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

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');
}

这篇关于如何在JavaScript中的同一个元素上应用长时间点击事件和doubleclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆