按钮功能,如果按钮被按下 10 秒钟

Button function if the button is pressed for 10 seconds?

本文关键字:按钮 秒钟 功能 如果      更新时间:2023-09-26

我试图找到一种仅在用户按下/单击按钮 10 秒时才执行按钮功能的方法。

普通按钮功能为:

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

那么有没有办法从用户按下按钮并一直按下的那一刻起计算秒数,(连续按下而不点击而不是点击),当秒达到 10 时,该功能将执行?

您需要计时器,按住鼠标时设置一个计时器,释放鼠标时清除计时器。

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

小提琴

你必须使用鼠标向下和鼠标向上而不是单击事件,

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

演示

jQuery LongPress 插件将为您处理这个问题。

https://github.com/vaidik/jquery-longpress

您可以在函数执行之前设置 delay 参数。

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>

小提琴http://jsfiddle.net/5z94y2z5/

您需要使用鼠标按下和鼠标向上事件

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