[removed] long click for a bookmarklet

2019-06-27 20:01发布

问题:

I need to recognize a long click in a JavaScript bookmarklet. So, I cannot use jQuery, neither onclick() event and similar. Is it possible, and how?

回答1:

onmousedown, call setTimeout() for the duration of your long click. If the timeout is allowed to expire, it will call its function to do whatever you hoped to do on the long click. However, onmouseup you cancel the setTimeout() if it has not yet expired.

<script type='text/javascript'>
// t will hold the setTimeout id
// Click for 1 second to see the alert.
var t;
</script>

<button onmousedown='t=setTimeout(function(){alert("hi");}, 1000);' onmouseup='clearTimeout(t);'>Clickme</button>

Here it is in action in jsfiddle



回答2:

Isn't a long click just a click where mousedown and mouseclick events are considerably long away from each other? In order to solve that you could just measure the time it takes from a mousedown event to the click event and check if it is, e.g. longer than two seconds (or whatever you desire).

You can access the current milliseconds since 01.01.1970 via new Date().getTime(). Given that I would intuitively check a "long click" like that.

$(".selector").mousedown(function() {
    $(this).data("timestamp", new Date().getTime());
}).click(function(event) {
    var e = $(this);

    var start = e.data("timestamp");
    e.removeData("timestamp");

    if (start && new Date().getTime() - start > YOUR_DESIRED_WAIT_TIME_IN_MILLISECONDS) {
        // Trigger whatever you want to trigger
    } else {
        event.preventDefault();
        event.stopPropagation();
    }
});


回答3:

Late reply, but instead of click / long click to provide two different actions, you might want to consider click / double click.

First click: Record time and then timer to perform action1 in 500 miliseconds.

Second click: If time since last click is short, cancel timer and perform action2. If time since last click is long, then this is a first click.

Nothing stops you from using triple click, etc.