1

我如何知道用户按住鼠标按钮(网页上的任何位置)多长时间?我想在用户按住鼠标按钮至少 2-3 秒时执行一个功能(最好在此过程中取消鼠标按下)。这可能吗?

4

4 回答 4

15

Here you go:

$(window).mousedown(function(e) {
    clearTimeout(this.downTimer);
    this.downTimer = setTimeout(function() {
        // do your thing 
    }, 2000);
}).mouseup(function(e) {
    clearTimeout(this.downTimer);
});

Live demo: http://jsfiddle.net/simevidas/Pe9sq/2/

于 2011-05-22T22:07:01.817 回答
1

Off hand I would experiment with $("body").mousedown(function(){}) using jQuery and $("body").mouseup(function(){}). I guess you can start a timer which will call function in 2 to 3 seconds. If the mouseup event occurs, then you can cancel the timer. You could probably test it with a simple script but you might have to look at cases where the click might have occurred because a link or button was clicked on the page. But as a starting point I would experiment with the $("body").mousedown and $("body").mouseup. If I have chance I'll see if I can send a code sample.

于 2011-05-22T22:01:04.400 回答
0

尝试这个:

function WhateverYoudLikeToExecWithinNext3Seconds(){
    // Code goes here.
}

element.addEventListener('mousedown', function(){
    setTimeout(function(){WhateverIdLikeToExecWithin3Seconds();}, 3000);
}, false);
于 2011-05-22T22:13:49.910 回答
0

Check out this one. http://jsfiddle.net/b1Lzo60n/

Mousedown starts a timer that checks if mouse is still down after 1 second.

<button id="button">Press me</button>
<div id="log"></div>

Code:

var mousedown = false;
var mousedown_timer = '';
$('#button').mousedown(function(e) {
    mousedown = true;
    $('#log').text('mousedown...');
    mousedown_timer = setTimeout(function() {
        if(mousedown) {
            $('#log').text('1 second');
        }
    }, 1000);
}).mouseup(function(e) {
    mousedown = false;
    clearTimeout(mousedown_timer);
    $('#log').text('aborted');
});
于 2015-02-26T05:23:02.677 回答