2012-09-24 74 views
21

我已經閱讀了有關這種情況的幾個答案,但沒有一個解決方案正在工作。區分點擊vs mousedown/mouseup

我試圖做基於用戶是否點擊的元素,或向下按住鼠標使用jQuery該元素的不同的事情。

可以做到這一點嗎?

+1

@MrOBrian在鼠標按下設置全局變量和mouseup爲true/false,那麼在點擊方法檢查變量,但鼠標鬆開始終閃光第一 – aperture

+0

你可以嘗試使用鼠標上的計時器下來,將然後設置一個變量或綁定正確的事件,以便知道按鈕是否按住了至少一段時間。 – MrOBrian

回答

15

這裏有一個方法

  1. 設置爲true
  2. 變量
  3. 使調用時
  4. 有一個計時器(setTimeout()),將其設置爲false的功能開始鼠標按下倒計時()
  5. 上的mouseup,清除超時,並檢查是否變量是真還是假
  6. 如果是假的,叫你想在點擊
  7. 在任何情況下發生的功能,設置變量回真正的

這將做你想做的。 這裏是展示它如何工作的jsfiddle:http://jsfiddle.net/zRr4s/3/

+0

幹得好@daveyfaherty,你真的幫了我。 – eyalewin

25

當按下左或右(或中間)onmousedown事件將觸發。同樣,當任何按鈕被釋放時,onMouseUp都會觸發。單擊在對象上,當鼠標移動,然後關閉它,而onMouseUp將觸發如果你點擊和其他地方按住按鈕,然後釋放它的對象上面onmousedown事件仍將觸發。當按下和在同一對象上釋放鼠標左鍵

的onClick纔會觸發。如果你關心的秩序,如果相同的對象有3點所有設置的事件,這是onmousedown事件,onMouseUp,然後的onClick。每個甚至應該只觸發一次。

詳情:

+0

是的,但我希望onClick在mousedown和mouseup之間的時間足夠長時不會觸發。我現在比較時間戳的事件,而這種作品。 – aperture

8

下面是一個同時支持點擊和持有的解決方案:

// 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(); 
} 

這裏有一個演示:http://jsfiddle.net/M7hT8/1/

最初基於daveyfaherty的解決方案。 我知道這個問題是前一陣子,但我分享我的解決方案,任何人通過搜索發現這一點。

+0

而且確實有幫助。謝謝! – GuyC

+0

我爲Cordova應用程序使用此解決方案,但使用新的指針事件API來統一支持觸摸和鼠標輸入。請參閱https://mobiforge.com/design-development/html5-pointer-events-api-combining-touch-mouse-and-pen – HEXcube

-1
//last mouse coordinate 
var mouseX = 0; 
//epsilon interval 
var mouseEps = 10; 

function mouseDownHandler(e) { 
    e.preventDefault(); 
    mouseX = e.clientX; 
}; 

function mouseUpHandler(e) { 
    e.preventDefault(); 
    if (Math.abs((mouseX - e.clientX)) < mouseEps) { 
     clickHandler(e); 
    } 
}; 

function clickHandler(e) { 
};