在 caph-list 项目上检测长按 Enter/OK 键

Detect Long Press on Enter/OK Key on a caph-list Item

我需要检测长按 Enter/OK 键在 caph-list 项目上。我正在使用下面的代码:

$("#channels-list-container").caphList({
    items: MyTVApp.groupChannels,
    template: "channels-list-item-template",
    direction: "vertical",

}).on("focused", function(event) {
    MyTVApp.focusedChannelIndex = Number(event.target.dataset.focusableName.split("channel")[1]);

}).on("selected", function(event) {
    var channelIndex = Number(event.target.dataset.focusableName.split("channel")[1]);
    var file = event.target.dataset.file;
    MyTVApp.displayPlayingScreen(file);
});

当焦点位于 caph-list 项目时,如何检测长按 Enter/OK 键?

由于我还不能发表评论,所以我会把我的答案放在这里。正如该人在评论中所说,您可以在按下按钮或按下按钮时启动计时器,然后在按下按钮时停止计时器并查看它被按下了多长时间,如果时间在您预期的持续时间内或更长,然后你知道这是一个足够长的新闻。检查后,您可以清除计时器。

正如@basic 已经提到的,您需要一些机制来检测第一次按键事件和按键事件之间经过的时间。

下面的代码应该为您提供一个示例,说明如何实现这一点。请记住,这只是一个示例,可能需要根据您的特定需求进行调整,但它被设计为一个独立的通用功能;它与您的应用程序逻辑没有任何直接联系。

如果您运行下面的代码示例,聚焦输入字段并按回车键至少一秒钟,您应该会看到一个检测到该事件的控制台日志条目。

// Long-key-press event detection
(function() {
  var duration = 1000,
      timer = null;

  $(document).on('keydown', function(event) {
    // Check if timer is already running.
    if(timer !== null) return;

    // Start new timer.
    timer = window.setInterval(function() {
      // Trigger longKeyPress event on the currently selected element when the timer finishes.
      $(event.target).trigger({
        type: 'longKeyPress',
        key: event.key,
        keyCode: event.keyCode,
        which: event.which
      });
    }, duration);
  });
  
  $(document).on('keyup', function(event) {
    if(timer === null) return;
    
    // Clear running timer.
    window.clearTimeout(timer);
    timer = null;
  });
})();

// Application logic
(function() {
  // Bind to custom longKeyPress event.
  $('#channels-list-container').on('longKeyPress', function(event) {
    if(event.key === "Enter") {
      console.log('Long [Enter] key press detected on targeted element!');
    }
  });
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="channels-list-container" type="text" />