按钮在按下10秒后的功能是什么?

4

我正在寻找一种方法,只有在用户按下/点击按钮10秒钟后才执行按钮功能。

普通的按钮功能是:

$( "#target" ).click(function() {
alert( "Handler for .click() called." );
});

那么有没有办法从用户按下按钮并继续保持按压的时刻开始计算秒数(连续按压而不是点击或轻触),当秒数达到10时,函数将执行?


https://dev59.com/k2855IYBdhLWcg3w6Y1q#4080508 - Jamie Dunstan
5个回答

7

您需要使用计时器,在鼠标按下时设置一个计时器,在鼠标释放时清除它。

$( "#target" ).on({
    mousedown: function() {
        $(this).data('timer', setTimeout(function() {
              foo();
        }, 10000));
    },
    mouseup: function() {
        clearTimeout( $(this).data('timer') );
    }
});

FIDDLE


所以 foo(); 是我的函数,如果我持续按下按钮 3 秒钟,它将执行吗? - user3806613
@user3806613 - 没错! - adeneo
不错...我会在5分钟内接受这个答案... - user3806613
60.000 是 60 秒,因为 1000 是 1 秒。请参阅 https://www.w3schools.com/jsref/met_win_settimeout.asp。 - koppor

0

你需要使用mousedown和mouseup事件,而不是click事件。

var timeOut = 0;
$("#target").mousedown(function () {
    clearTimeout(timeOut);
    timeOut = setTimeout(function () {
        console.log("Handler for .click() called.");
    }, 10000);
});
$(document).mouseup(function () {
    clearTimeout(timeOut);
    console.log("stop");
})

演示


0
jQuery的LongPress插件将为您处理此操作。
https://github.com/vaidik/jquery-longpress

在函数执行之前,您可以设置延迟参数。


0

JS

var threshold = 10000, timeOne, timeTwo;
$('#t10').mousedown(function(){
    timeOne = new Date();
}).mouseup(function(){
    timeTwo = new Date();
    if(timeTwo - timeOne >= threshold){
        alert('Do what you want');
        timeOne = 0;
    }else{
        console.log('Released early');
    }
});

HTML

<button  id="t10">XX</button>

Fiddle http://jsfiddle.net/5z94y2z5/


0

你需要使用mousedown和mouseup事件

http://api.jquery.com/mousedown/ http://api.jquery.com/mouseup/

var pressedtensecondos = false;
var timer = null;

$( "#target" ).mousedown(function() {
  timer = setTimeout(function() { pressedtensecondos = true; }, 10000);
});

$( "#target" ).mouseup(function() {
  clearTimeout(timer);
  
  if(pressedtensecondos)
    alert('ten seconds');

  pressedtensecondos = false;
});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接