用键盘组合键给你的页面注入更多乐趣吧!

用键盘组合键给你的页面注入更多乐趣吧!

前言

大家好!在我们日常开发中,经常会使用到各种各样的快捷键。你是否想过使用键盘组合键给你的页面添加一些特殊功能或者其他的事情呢?本文就让我们一起用键盘组合键来做一些好玩的事情吧!

基本思路

大致思路很简单,相信大家日常工作中也或多或少的接触过,就是监听键盘按键,然后执行相应的操作。

说到键盘按键,第一个想到的就应该是获取keycode值,可是在我实际使用的时候,发现keycode已经被弃用,取而代之可以使用codekey。这里就是用key来获取按键信息。通过监听keydown事件,获取按键信息,然后判断是否符合条件,符合条件则执行相应的操作。

需要注意的一点就是为了防止组合键是一些带有功能的快捷键,比如ctrl + c等等, 符合条件之后,还需要单独去取消一下这个组合键的默认操作,否则除了执行自定义的功能外还会执行组合键原有的功能。

基础代码实现

 window.addEventListener(
    'keydown',
    function(event) {
      if (event.defaultPrevented) {
        return; // 如果已取消默认操作,则不应执行任何操作
      }
      var handled = false;
      if (event.key !== undefined) {
        if (event.key.toLocaleLowerCase() === 's' && event.ctrlKey && event.shiftKey) {
          //do somthing...
          handled = true;
        }
      } else if (event.keyCode !== undefined) {
        if (event.keyCode === 88 && event.ctrlKey && event.shiftKey) {
          //do somthing...
          handled = true;
        }
      }

      if (handled) {
        // 取消默认操作 如果事件已处理,则禁止“双重操作”
        event.preventDefault();
      }
    },
    true
  );

效果展示

将上面的代码放到你的程序中执行后,就可以使用快捷键了。具体效果是,当我们按下指定的组合键时,会执行相应的操作。

用键盘组合键给你的页面注入更多乐趣吧!

完善一下

根据前面的实现方式,我们可以进一步完善,做到一些更好玩的事情。比如可以简单封装一下,做到事先设置好一组快捷键,然后开启全局监听,后面就可以在页面里面使用啦。

function ShortcutManager() {
  this.pressedKeys = []; // 存储按下的所有按键信息
  this.onShortcutMatchCallback = null;

  this.handleKeyPress = this.handleKeyPress.bind(this);
}

// 设置自定义的快捷键组合
ShortcutManager.prototype.setShortcut = function(shortcut) {
  this.shortcut = shortcut;
};

// 判断是否匹配
ShortcutManager.prototype.recordKey = function(key) {
  const currentTime = new Date().getTime();
  const lastPressedTime = this.pressedKeys.length > 0 ? this.pressedKeys[this.pressedKeys.length - 1].time : 0;

  // 如果按下的按键和之前按下的按键间隔超过500毫秒,则清空已记录的按键信息
  if (currentTime - lastPressedTime > 500) {
    this.pressedKeys = [];
  }

  this.pressedKeys.push({ key, time: currentTime });

  if (
    this.pressedKeys.length === this.shortcut.length &&
    this.pressedKeys.every((pressedKey, index) => pressedKey.key === this.shortcut[index])
  ) {
    // 匹配成功,清空前面存储的按键信息
    this.pressedKeys = [];

    if (this.onShortcutMatchCallback) {
      this.onShortcutMatchCallback();
    }
    return true;
  }
  return false;
};

ShortcutManager.prototype.onShortcutMatch = function(callback) {
  this.onShortcutMatchCallback = callback;
};

// 开始监听键盘按键事件
ShortcutManager.prototype.startListening = function() {
  window.addEventListener('keydown', this.handleKeyPress);
};

ShortcutManager.prototype.stopListening = function() {
  window.removeEventListener('keydown', this.handleKeyPress);
};

ShortcutManager.prototype.handleKeyPress = function(event) {
  if (event.defaultPrevented) {
    return; // 如果已取消默认操作,则不应执行任何操作
  }

  const key = event.key;

  const shortcutMatched = this.recordKey(key);

  if (shortcutMatched) {
    event.preventDefault(); // 取消默认操作
  }
};

具体使用方法相当的简单。第一步,声明一个对象,调用setShortcut方法,提前设置好你想设置的快捷键。第二步,设置好你需要触发的功能。最后一步,调用startListening开启监听就完成啦。具体代码如下:

const shortcutManager = new ShortcutManager();
// 设置键盘按键 上上下下左右左右baba
shortcutManager.setShortcut([
  'ArrowUp',
  'ArrowUp',
  'ArrowDown',
  'ArrowDown',
  'ArrowLeft',
  'ArrowRight',
  'ArrowLeft',
  'ArrowRight',
  'b',
  'a',
  'b',
  'a'
]);
shortcutManager.onShortcutMatch(function() {
  // 这里是匹配成功后触发的自定义操作
  // do soemthing
});

//开启键盘按键监听
shortcutManager.startListening();

关于键盘的key值

大多数情况下,Windows系统和macOS系统监听到的按键的key值是相同的,常用的需要区分的也就是ctrl,在macOS系统下,key值为meta。在Window系统下,ctrlkey值为Control。下面列出一些常用的按键的key值,如果需要了解所有的key值,请参考MDN

按键 event.key值
数字键 相应的数字字符,例如 0、1、2 等等。
F1 到 F12 功能键 F1、F2、F3 等等。
空格键 ” “。
回车键 “Enter”。
Tab 键 “Tab”。
退格键 “Backspace”。
删除键 “Delete”。
上、下、左、右箭头键 “ArrowUp”、”ArrowDown”、”ArrowLeft”、”ArrowRight”。
Ctrl、Alt、Shift 键 “Control”、”Alt”、”Shift”

写在最后

感谢大家的阅读!这篇文章旨在分享一些我平时遇到或者想到的一些有趣的技术,并且锻炼自己的写作能力。初期技术性可能没有那么强,如果大家有任何问题或者建议,欢迎大家和我讨论和指正。

再次感谢大家的阅读,谢谢!

原文链接:https://juejin.cn/post/7315224380590309430 作者:xllcc

(0)
上一篇 2023年12月22日 下午4:17
下一篇 2023年12月22日 下午4:27

相关推荐

发表回复

登录后才能评论