区分click vs mousedown/mouseup

ape*_*ure 21 jquery

我已经阅读了有关这种情况的stackoverflow的几个答案,但没有一个解决方案正在运行.

我试图根据用户是否单击一个元素来做不同的事情,或者使用jQuery将鼠标按住该元素.

有可能做到这一点吗?

Ant*_*iev 29

当按下左侧或右侧(或中间)时,onMouseDown将触发.同样,onMouseUp将在释放任何按钮时触发.onMouseDown即使在对象上单击鼠标然后移出它也会触发,而onMouseUp将在其他位置单击并按住按钮时触发,然后将其释放到对象上方.

只有在同一个对象上按下并释放鼠标左键时,onClick才会触发.如果您关心订单,如果同一个对象设置了所有3个事件,则它是onMouseDown,onMouseUp,然后是onClick.每个偶数只应该触发一次.

细节:


dav*_*rty 16

这是一种方法

  1. 将变量设置为true
  2. 创建一个在调用时将其设置为false的函数
  3. 有一个计时器(setTimeout())开始倒计时mousedown()
  4. 在mouseup上,清除超时,并检查变量是true还是false
  5. 如果是假,请在点击时调用您想要发生的功能
  6. 无论如何,将变量设置为true

这将做你想要的.这是一个jsfiddle显示它可能如何工作:http://jsfiddle.net/zRr4s/3/


bas*_*007 9

这是一个支持点击和保持的解决方案:

// Timeout, started on mousedown, triggers the beginning of a hold
var holdStarter = null;
// Milliseconds to wait before recognizing a hold
var holdDelay = 500;
// Indicates the user is currently holding the mouse down
var holdActive = false;
// MouseDown
function onMouseDown(){
    // Do not take any immediate action - just set the holdStarter
    //  to wait for the predetermined delay, and then begin a hold
    holdStarter = setTimeout(function() {
        holdStarter = null;
        holdActive = true;
        // begin hold-only operation here, if desired
    }, holdDelay);
}
// MouseUp
function onMouseUp(){
    // If the mouse is released immediately (i.e., a click), before the
    //  holdStarter runs, then cancel the holdStarter and do the click
    if (holdStarter) {
        clearTimeout(holdStarter);
        // run click-only operation here
    }
    // Otherwise, if the mouse was being held, end the hold
    else if (holdActive) {
        holdActive = false;
        // end hold-only operation here, if desired
    }
}
// Optional add-on: if mouse moves out, then release hold
function onMouseOut(){
    onMouseUp();
}
Run Code Online (Sandbox Code Playgroud)

这是一个演示:http://jsfiddle.net/M7hT8/1/

最初基于daveyfaherty的解决方案.我知道这个问题是从不久前开始的,但是我正在为通过搜索找到这个问题的人分享我的解决方案.