如何在元素上同时使用onclick和ondblclick? [英] How to use both onclick and ondblclick on an element?

查看:143
本文介绍了如何在元素上同时使用onclick和ondblclick?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面上有一个元素需要附加onclick和ondblclick事件处理程序。单击发生时,它应该执行与双击不同的操作。当我第一次开始尝试这项工作时,我的头开始旋转。显然,双击时onclick总会触发。所以我尝试使用这样的基于超时的结构......

I have an element on my page that I need to attach onclick and ondblclick event handlers to. When a single click happens, it should do something different than a double-click. When I first started trying to make this work, my head started spinning. Obviously, onclick will always fire when you double-click. So I tried using a timeout-based structure like this...

window.onload = function() {
  var timer;
  var el = document.getElementById('testButton');

  el.onclick = function() {
    timer = setTimeout(function() { alert('Single'); }, 150);        
  }

  el.ondblclick = function() {
    clearTimeout(timer);
    alert('Double');
  }
}

但是我的结果不一致(使用IE8)。它可以正常工作很多次,但有时我会两次收到单一警报。

But I got inconsistent results (using IE8). It would work properly alot of times, but sometimes I would get the "Single" alert two times.

以前是否有人这样做过?有没有更有效的方法?

Has anybody done this before? Is there a more effective way?

推荐答案

和Matt一样,当我稍微增加超时值时,我的体验要好得多。此外,为了缓解单击触发两次的问题(无论如何我无法使用更高的计时器重现),我在单击处理程序中添加了一行:

Like Matt, I had a much better experience when I increased the timeout value slightly. Also, to mitigate the problem of single click firing twice (which I was unable to reproduce with the higher timer anyway), I added a line to the single click handler:

el.onclick = function() {
    if (timer) clearTimeout(timer);
    timer = setTimeout(function() { alert('Single'); }, 250);        
}

这样,如果click已设置为fire,它将自行清除避免重复的单一警报。

This way, if click is already set to fire, it will clear itself to avoid duplicate 'Single' alerts.

这篇关于如何在元素上同时使用onclick和ondblclick?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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