35

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

可能吗 ?

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

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

});
4

12 回答 12

39

添加一个限制,只允许在鼠标按下 2 秒后发生点击。

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

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

于 2013-01-29T16:00:05.217 回答
31

只需观察两者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!');   
        }
    } );

}());
于 2013-01-29T16:01:20.143 回答
3

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

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

$('div').on('press', function(e) {
    console.log(this, e);
});
于 2015-04-09T01:09:25.447 回答
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!');   
    }
});
于 2017-08-04T01:24:27.000 回答
3

我知道这个问题现在已经很老了,但我一直在寻找类似的东西,发现 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();
  } );

} );
于 2016-03-07T16:33:25.923 回答
2

升级和合并EditorKevin B的回复,您可以拥有一个功能齐全的、多 div、hold-catcher:

    // 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');
    });
于 2013-11-10T01:22:35.283 回答
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);
});
于 2013-01-29T16:04:44.817 回答
2

所以这显然在未来还有很长的路要走,但是对于仍然想要这样做的人来说,一个超级简单且非常优雅的方法是将 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>

于 2019-04-18T15:37:02.417 回答
1

当您检测到对 div 的点击时,您可以获得时间戳,这要归功于mousedown. 同样,您可以在检测到点击释放时获取时间戳,这要归功于mouseup.

然后您需要比较这两个时间戳,如果它们大于 2 秒(或 2000 毫秒),则执行您的函数。

于 2013-01-29T15:59:44.007 回答
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;
    });
于 2014-01-14T14:26:54.363 回答
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/

于 2014-08-01T16:28:58.040 回答
0

我们可以计算鼠标点击离开时的时间差。timestamp当您单击并释放 abuttondiv 使用mousedownand时,我们可以得到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>

于 2019-08-07T13:19:19.573 回答