如何检测Jquery中div的长按?

时间:2013-01-29 15:53:45

标签: jquery triggers

当用户在div上按2 seconds时,我想执行一些功能。

有可能吗?

这是我检测div上点击的代码

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

});

12 个答案:

答案 0 :(得分:33)

添加一个仅允许在mousedown 2秒后发生点击的油门。

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

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

答案 1 :(得分:27)

只需观看mousedownmouseup,然后计算差异。 Here's an example

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

}());

答案 2 :(得分:3)

我知道这个问题现在已经很老了,但我正在寻找类似的东西,并发现Buley的答案接近我的需要。我想我发布了我用它做的事情,让它在没有鼠标的情况下运行,有点像Android长触控。

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

} );

答案 3 :(得分:3)

  

短按&长按事件 - 长按时禁止短按

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

答案 4 :(得分:2)

您可以使用以下代码(在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);
});

答案 5 :(得分:2)

升级和合并编辑 Kevin 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');
    });

答案 6 :(得分:2)

在这个问题被问到两年后,一个名为jQuery Finger的精彩插件被发明了:

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

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

答案 7 :(得分:1)

由于mousedown,您可以在检测到div上的点击时获取时间戳。同样,您可以通过mouseup检测点击发布时获取时间戳。

然后你需要比较这两个时间戳,如果它们大于2秒(或2000毫秒),那么你执行你的功能。

答案 8 :(得分:1)

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

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

答案 9 :(得分:1)

简单。不需要长时间不必要的编码。

(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/

答案 10 :(得分:1)

因此,这显然是未来的漫长道路,但是对于仍然想要这样做的人来说,一种超简单且非常优雅的方法是将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>

答案 11 :(得分:0)

我们可以计算鼠标单击并离开时的时差。当您单击并使用timestampbutton

释放divmousedown时,我们可以获得mouseup

以下是检测简单点击和2 seconds长按的示例。在这里,我用button印刷机完成了印刷。同样,您可以使用div

$(document).ready(function () {

	var pressTime; // store the press time

	$("#pressHere").on('mouseup', function () {

		var holdTime = 2000; //2 milliseconds for long press

		if (new Date().getTime() >= (pressTime + holdTime))
			$("#status").text("It's a Long Press...");
		else
			$("#status").text("It's a Short Press...");
      
	}).on('mousedown', function () { // When Button Release
		
    pressTime = new Date().getTime();
    
	}).on('mouseleave', function () { 	// When Button Leave
		
    pressTime = 0;
    
	});

});
.input-bar-item {
    display: table-cell;
}
.button-item {
margin: 20px;
    width: 30%;
}
.width100 {
  width: 60%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


 <div class="input-bar-item button-item">
      <button class="btn btn-info" id="pressHere">Press Me</button>
</div>
<div class="input-bar-item width100" id="status"></div>