简体   繁体   English

如何在javascript中检测按下x秒的键?

[英]How to detect a key pressed for x seconds in javascript?

I need to detect when a user keep press a button for X second and call function in JavaScript. 我需要检测用户何时按下X秒按钮并在JavaScript中调用函数。 Could you point me out in right direction? 你能指出我正确的方向吗?

You can use a setTimeout function on the keydown event which will fire after X seconds to compare the time that event was triggered to the last time a keyup was triggered - if at all. 您可以在keydown事件上使用setTimeout函数 ,该事件将在X秒后触发,以比较触发事件的时间与上次触发keyup时间 - 如果有的话。

var lastKeyUpAt = 0;

$(elem).on('keydown', function() {
    // Set key down time to the current time
    var keyDownAt = new Date();

    // Use a timeout with 1000ms (this would be your X variable)
    setTimeout(function() {
        // Compare key down time with key up time
        if (+keyDownAt > +lastKeyUpAt)
            // Key has been held down for x seconds
        else
            // Key has not been held down for x seconds
    }, 1000);
});

$(elem).on('keyup', function() {
    // Set lastKeyUpAt to hold the time the last key up event was fired
    lastKeyUpAt = new Date();
});

elem here is the element you're wanting to handle the event on. elem这里是你想要处理事件的元素。

JSFiddle demo . JSFiddle演示

Check out the jquery docs, they're super awesome. 查看jquery文档,它们非常棒。 Something like this could give you the gist, though. 不过,像这样的东西可以给你一个要点。

var keyTO,
    seconds = 5;
$( "#i" ).on({
  keypress: function(e) {
        if(keyTO) {
            clearTimeout(keyTO);
            keyTO = null;
        }
        keyTO = setTimeout(someFn, seconds*1000);
  },
  keyup: function(e) {
      clearTimeout(keyTO);
      keyTO = null;
  }
});
function someFn() {
    // only called after full timeout
    alert('Sweet.');
}

Watch for keydown and keyup events. 观察keydownkeyup事件。 jQuery's keydown event triggers recursively based on the user's keyboard settings for press and hold of keys. jQuery的keydown事件基于用户按下和按住键的键盘设置递归触发。 You can alternatively set your own recursive checking timeout if you would like to check this more/less frequently or abstract your checking away from varying user's keyboard settings. 您可以选择设置自己的递归检查超时,如果您想更频繁/更不频繁地检查,或者从不同用户的键盘设置中抽象出来。

This code (thanks to nbrooks for the prompting), monitors each key down event as their own instance, and so will allow for multiple keys to be press and held on a keyboard, each with their own triggertimes. 这段代码(感谢nbrooks的提示),将每个按键事件监视为自己的实例,因此可以按住键盘上的多个按键,每个键都有自己的触发器。

$(function(){
    var keyDownArray = {};
    var triggerTime = 3000; // number of ms to trigger function at

    var keyDownEvent = function(e){
        // use the event keyCode as a unique identifier
        if(!(e.keyCode in keyDownArray) ){
            // use the event keyCode as a unique identifier
            // use setTimeout to make sure trigger only occurs once
            keyDownArray[e.keyCode] = setTimeout(function(){
                // call your function here (can pass in e.keyCode if function requires custom functions on a per key basis)
                console.log('triggered for key '+e.keyCode);
            }, triggerTime);
        }
    }

    var keyUpEvent = function(e){
        // on key release, clearTimeout and delete object key
        clearTimeout(keyDownArray[e.keyCode]);
        delete keyDownArray[e.keyCode];
    };

    $(document).on('keydown', keyDownEvent)
        .on('keyup', keyUpEvent);
});

JSFiddle Demo JSFiddle演示

PS. PS。 it may be worth adding a throttler (something like Ben Almans debounce/throttle plugin ) to decrease the potential load of this function 可能值得添加一个节流器(类似Ben Almans去抖/油门插件 )以减少此功能的潜在负载

jsFiddle 的jsfiddle

You can accomplish this simply by recording the time at which a key is pressed, and then checking the time again when the key is released. 您只需记录按下按键的时间,然后在释放按键时再次检查时间即可完成此操作。 Construct a JS object which maps key-codes to dates. 构造一个将键代码映射到日期的JS对象。

On keyDown, record the key and current time (if it's not already set—some keys trigger multiple keydowns while being held). 在keyDown上,记录键和当前时间(如果尚未设置 - 某些键在保持时触发多个键控)。 On keyUp, find the time difference, clear the map entry, and then process accordingly: 在keyUp上,找到时差,清除映射条目,然后相应地处理:

$(function () {
    var keyTimes = {};

    $(document).keydown(function (e) {
        if (!keyTimes["key" + e.which]) {
            keyTimes["key" + e.which] = new Date().getTime();
        }
    });

    $(document).keyup(function (e) {
        if (keyTimes["key" + e.which]) {
            var x = new Date().getTime() - keyTimes["key" + e.which];
            delete keyTimes["key" + e.which];

            // key was held for x/1000.0 seconds
        }
    });
});

Use keydown() and keyup() to check for the keypress. 使用keydown()和keyup()来检查按键。 Get the current system time with keydown() and compare that with the current system time when you get the keyup(). 使用keydown()获取当前系统时间,并在获得keyup()时将其与当前系统时间进行比较。

var starttime;
var curKey;

$('#seconds-counter').keydown(function(e) {
  if (curKey != e.which) {
    var d = new Date();
    starttime = d.getTime();
    $('#down-time').text(starttime);
    curKey = e.which;
  }
});

$('#seconds-counter').keyup(function() {
  var d = new Date();
  var endTime = d.getTime();
  $('#up-time').text(endTime);
  var timeTaken = endTime - starttime;
  $('#result-val').text(timeTaken / 1000);
  curKey = null;
});

JS Fiddle JS小提琴

(Edit: forgot the last bit :-) ) Call your function at the end of the keyup(), after curKey = null. (编辑:忘记了最后一位:-))在curKey = null之后,在keyup()的末尾调用你的函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM