我已經閱讀了有關這種情況的幾個答案,但沒有一個解決方案正在工作。區分點擊vs mousedown/mouseup
我試圖做基於用戶是否點擊的元素,或向下按住鼠標使用jQuery該元素的不同的事情。
可以做到這一點嗎?
我已經閱讀了有關這種情況的幾個答案,但沒有一個解決方案正在工作。區分點擊vs mousedown/mouseup
我試圖做基於用戶是否點擊的元素,或向下按住鼠標使用jQuery該元素的不同的事情。
可以做到這一點嗎?
這裏有一個方法
setTimeout()
),將其設置爲false的功能開始鼠標按下倒計時()這將做你想做的。 這裏是展示它如何工作的jsfiddle:http://jsfiddle.net/zRr4s/3/
幹得好@daveyfaherty,你真的幫了我。 – eyalewin
當按下左或右(或中間)onmousedown事件將觸發。同樣,當任何按鈕被釋放時,onMouseUp都會觸發。單擊在對象上,當鼠標移動,然後關閉它,而onMouseUp將觸發如果你點擊和其他地方按住按鈕,然後釋放它的對象上面onmousedown事件仍將觸發。當按下和在同一對象上釋放鼠標左鍵
的onClick纔會觸發。如果你關心的秩序,如果相同的對象有3點所有設置的事件,這是onmousedown事件,onMouseUp,然後的onClick。每個甚至應該只觸發一次。
詳情:
是的,但我希望onClick在mousedown和mouseup之間的時間足夠長時不會觸發。我現在比較時間戳的事件,而這種作品。 – aperture
下面是一個同時支持點擊和持有的解決方案:
// 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的解決方案。 我知道這個問題是前一陣子,但我分享我的解決方案,任何人通過搜索發現這一點。
//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) {
};
@MrOBrian在鼠標按下設置全局變量和mouseup爲true/false,那麼在點擊方法檢查變量,但鼠標鬆開始終閃光第一 – aperture
你可以嘗試使用鼠標上的計時器下來,將然後設置一個變量或綁定正確的事件,以便知道按鈕是否按住了至少一段時間。 – MrOBrian