如何在 Jquery 中检测 div 上的长按?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14586883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:44:25  来源:igfitidea点击:

How to detect a long press on a div in Jquery?

jquerytriggers

提问by Steffi

I would like to execute some function when the user presses for 2 secondson a div.

我想在用户按下2 secondsdiv时执行一些功能。

Is it possible ?

是否可以 ?

Here is my code to detect the click on the div

这是我检测 div 点击的代码

$('div').mousedown(function() {

});

回答by Kevin B

Add a throttle that only allows the click to happen after 2 seconds of mousedown.

添加一个仅允许在鼠标按下 2 秒后发生点击的节流阀。

var timer;
$('div').on("mousedown",function(){
    timer = setTimeout(function(){
        alert("WORKY");
    },2*1000);
}).on("mouseup mouseleave",function(){
    clearTimeout(timer);
});

Edit: I added mouseleave too since if the mouse leaves the element and then triggers mouseup, it won't stop the timer.

编辑:我也添加了 mouseleave ,因为如果鼠标离开元素然后触发 mouseup ,它不会停止计时器。

回答by buley

Just watch both mousedownand mouseupand calculate the difference. Here's an example.

刚才看都mousedownmouseup和计算差值。这是一个例子

(function() { 

    // how many milliseconds is a long press?
    var longpress = 3000;
    // holds the start time
    var start;

    jQuery( "#pressme" ).on( 'mousedown', function( e ) {
        start = new Date().getTime();
    } );

    jQuery( "#pressme" ).on( 'mouseleave', function( e ) {
        start = 0;
    } );

    jQuery( "#pressme" ).on( 'mouseup', function( e ) {
        if ( new Date().getTime() >= ( start + longpress )  ) {
           alert('long press!');   
        } else {
           alert('short press!');   
        }
    } );

}());

回答by Thomas Hunter II

In the two years since this question was asked an awesome plugin called jQuery Finger was invented:

在提出这个问题后的两年里,发明了一个很棒的插件 jQuery Finger:

http://ngryman.sh/jquery.finger/

http://ngryman.sh/jquery.finger/

$('div').on('press', function(e) {
    console.log(this, e);
});

回答by Tim Howey

I know this question is pretty old now, but I was looking for something like this and found that Buley's answer was close to what I needed. I figured I'd post what I've done with it to have it function without the mouse up, sort of like an Android longtouch.

我知道这个问题现在已经很老了,但我一直在寻找这样的问题,发现 Buley 的答案接近我所需要的。我想我会发布我对它所做的事情,让它在没有鼠标的情况下运行,有点像 Android longtouch。

// Set the duration of the long press and declare a couple variables
var longpress = 1000;
var start;
var divMouseDown;                       

// Check for mousedown on the element of choice
$("#element").on('mousedown', function(e){
  // Get the time it was clicked
  start = new Date().getTime();

  // See if mouse is still being held down after the longpress duration
  divMouseDown = setTimeout(function(){
    // What we want to happen when mouse is clicked and held for 1 second
  }, longpress);

  // If the mouse leaves the element or is released before the long touch event, 
  // reset variables and stop the function from triggering          
  $("#element").on('mouseup mouseleave', function(){
    if (divMouseDown) {
      clearTimeout(divMouseDown);
    }
    start = 0;
    e.stopPropagation();
  } );

} );

回答by Ond?ej Golasowski

Short-click & Long-click events - short press prevented in long press

短按和长按事件 - 长按防止短按

//from e-OS menu script
var longpress = 800;
var start;
var timer;

//short press - show e-OS system menu
//long press - show e-OS settings
$( "#e-OS-menu" ).on( 'mousedown', function( e ) {
    start = new Date().getTime();
    timer = setTimeout(function(){ console.log('long press!'); }, longpress)
}).on( 'mouseleave', function( e ) {
    start = 0;
    clearTimeout(timer);
}).on( 'mouseup', function( e ) {
    if ( new Date().getTime() < ( start + longpress )  ) {
       clearTimeout(timer);
       console.log('short press!');   
    }
});

回答by Mathieu Rodic

You can use the following code (tested in JSFiddle):

您可以使用以下代码(在JSFiddle 中测试):

$('#foo').mousedown(function(){
   $(this).data('lastPressed', new Date().getTime());
}).mouseup(function(){
    var lastPressed = $(this).data('lastPressed');
    if (lastPressed){
        var duration = new Date().getTime() - lastPressed;
        $(this).data('lastPressed', false);
        if (duration > 2000) {
            alert('Your click lasted more than 2 seconds.');
        } else {
            alert('Your click lasted less than 2 seconds.');
        }
    }
}).mouseout(function(){
    $(this).data('lastPressed', false);
});

回答by user1492723

Upgrading and merging Editorand Kevin Breplies you can have a fully functional, multi divs, hold-catcher with:

升级和合并EditorKevin B 的回复,您可以拥有一个功能齐全的、多 div 的、具有以下功能的捕获器:

    // Global delta msec timeout
    var delta = 1500;

    $("#foo").on('mousedown', function(event) {

        var thisElement = $(event.currentTarget);
        var deltaTimer = setTimeout(function(){

            console.log('long press!');
            thisElement.removeData('startTimestamp');
        }, delta);

        thisElement.data('startTimestamp', new Date().getTime());
        thisElement.data('timer', deltaTimer);
    }).on('mouseleave', function(event) {

        var thisElement = $(event.currentTarget);
        clearTimeout(thisElement.data('timer'));

        thisElement.removeData('startTimestamp');
        thisElement.removeData('timer');
    }).on('mouseup', function(event) {

        var thisElement = $(event.currentTarget);
        var startTimestamp = thisElement.data('startTimestamp');
        clearTimeout(thisElement.data('timer'));

        if (startTimestamp !== undefined && !isNaN(parseInt(startTimestamp))) {

            if (new Date().getTime() >= (startTimestamp + delta))
               console.log('long press!');
            else
               console.log('short press!');
        }

        thisElement.removeData('startTimestamp');
        thisElement.removeData('timer');
    });

回答by PaRoxUs

This solution executes the action after the time you set. It also cancels the action if you leave the pressed element with the mouse.

此解决方案在您设置的时间之后执行操作。如果您用鼠标离开按下的元素,它也会取消操作。

var longpress={
        pressed:false,
        longpressed:false,
        presstime:1000
    };

$('#element').on( 'mousedown' , function( event ) {
        longpress.longpressed=false;
        longpress.pressed=true;
        longpress.timeout=setTimeout(function() {
            longpress.longpressed=true;
            //Long press action here!
        },longpress.presstime);
    }).on( 'mouseup' , function( event ) {
        clearTimeout(longpress.timeout);
        if (!longpress.longpressed && longpress.pressed) {
            longpress.pressed=false;
            //Short press action here!
        }
    }).on('mouseleave', function( event ) {
        clearTimeout(longpress.timeout);
        longpress.pressed=false;
    });

回答by Douglas David

Simple. No need for long uneccesary coding.

简单的。不需要冗长的不必要的编码。

(function(){
    // how many milliseconds is a long press?
    var offset = 500;

    $(".button").on('mousedown', function(e){
        // holds the start time
        $(this).data('start',new Date().getTime());
        $(this).addClass("selected");
    }).on('mouseup', function(e){
        if (new Date().getTime() >= ($(this).data('start') + offset)){
            //alert('ur click lasted for over 2 secs');
            $(this).addClass("selected");
        }else{
            $(this).removeClass("selected");
        }
    }).on('mouseleave', function(e){
        start = 0;
        //you can add destroy lingering functions on mouse leave
    });

}());

http://jsfiddle.net/donddoug/8D4nJ/

http://jsfiddle.net/donddoug/8D4nJ/

回答by Michael W

So this is obviously a long way in the future, but for people who want to do this still, a super simple and pretty elegant way to do this is by combining the clearTimeout function with mouseup / mouseout events:

所以这显然在未来还有很长的路要走,但是对于仍然想要这样做的人来说,一个超级简单而优雅的方法是将 clearTimeout 函数与 mouseup / mouseout 事件结合起来:

$('#button').mousedown(function(){
   var timer = setTimeout(
    () => {alert('long press occurred');}, 600
   );
}).mouseup(function(){
    clearTimeout(timer);
}).mouseout(function(){
    clearTimeout(timer);
});
#button {
  width: 50px;
  height: 50px;
  background-color: blue;
  color: white;
  display: flex;
  flex-direction: column;
  text-align: center;
  justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="button">press here</div>