Javascript,点击,双击并在同一元素中拖动 [英] Javascript, click, doubleclick and drag in the same element

查看:183
本文介绍了Javascript,点击,双击并在同一元素中拖动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个函数来判断用户是否点击,双击或拖动鼠标。

I'm in need of a function that figures out if the user is clicking, double-clicking or dragging the mouse.

因为它都发生在同一个使用正常事件的画布不工作。我通过谷歌发现了这一点:

Since it's all happening in the same canvas using the normal events doesn't work. I found this through google:


不应该为同一个元素绑定处理程序的click和dblclick
事件。触发的事件序列从浏览器到浏览器变化
,一些接收两个点击事件,
其他只有一个。如果不能避免对单一
和双击产生不同反应的接口,那么dblclick事件应该是在点击处理程序内模拟的
。我们可以通过在处理程序中保存
时间戳,然后将当前时间与随后点击时保存的时间戳记
进行比较来实现。如果差异很小,
就足够了,我们可以将点击视为双击。

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events and others only one. If an interface that reacts differently to single- and double-clicks cannot be avoided, then the dblclick event should be simulated within the click handler. We can achieve this by saving a timestamp in the handler, and then comparing the current time to the saved timestamp on subsequent clicks. If the difference is small enough, we can treat the click as a double-click.

在一个好的方式?

首先看看是否按下了点击(拖动)?当它被释放时作为点击处理它?然后如果再次点击doubleclick?

First see if the click is pressed (for drag)? When it is released treat it as a click? and then if clicked again doubleclick?

如何将此转换为代码?帮助赞赏。

How can I translate this to code? Help appreciated.

推荐答案

像下面这样应该让你开始,我使用jQuery只是为了更容易显示,这可以用纯JS实现,只是很多噪音

Something like the following should get you started, I'm using jQuery just to make it easier to show, this can be implemented with straight JS, it's just a lot of noise

$(function() {

  var doubleClickThreshold = 50;  //ms
  var lastClick = 0;
  var isDragging = false;
  var isDoubleClick = false;

  $node = ("#mycanvas");
  $node.click(function(){
    var thisClick = new Date().getTime();
    var isDoubleClick = thisClick - lastClick < doubleClickThreshold;
    lastClick = thisClick;
  });

  $node.mousedown(function() {
    mouseIsDown = true;
  });

  $node.mouseUp(function() {
    isDragging = false;
    mouseIsDown = false;
  });

  // Using document so you can drag outside of the canvas, use $node
  // if you cannot drag outside of the canvas
  $(document).mousemove(function() {
     if (mouseIsDown) {
       isDragging = true;
     }
  });
});

这篇关于Javascript,点击,双击并在同一元素中拖动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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