Google表格如何覆盖浏览器快捷方式? [英] How does Google Sheets override browser shortcuts?

查看:94
本文介绍了Google表格如何覆盖浏览器快捷方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个复杂的浏览器内应用程序,我想使用Chrome和/或其他主要浏览器当前使用的一些键盘快捷键.我在网上搜索,找不到覆盖浏览器快捷方式的方法,但是我看到Google表格只是我想要的那种功能:用户可以选择覆盖浏览器快捷方式的选项.

I'm creating a complicated in-browser app and I'd like to use some keyboard shortcuts that are currently used by Chrome and/or the other major browsers. I searched online and couldn't find a way to override browser shortcuts, but I saw that Google Sheets has just the kind of functionality I want: a user can select an option to override browser shortcuts.

Google表格如何完成这项工作?

How does Google sheets make this work?

更新:澄清一下,因为这已经引起了人们的不满:我知道event.preventDefault().问题在于,它似乎不适用于Ctrl + t(打开新标签页)之类的组合键.

Update: To clarify, since this has gotten some downvotes: I'm aware of event.preventDefault(). The problem is that it does not seem to work for key combinations like Ctrl + t (open new tab).

推荐答案

通常的想法是拦截该事件,并在该事件与您要覆盖的快捷方式相对应时对其调用event.preventDefault().例如,以下代码将阻止您按control-1导航到最左侧的标签:

The general idea is to intercept the event and call event.preventDefault() on it if it corresponds to a shortcut that you want to override. For example, the following code will prevent you from navigating to your leftmost tab if you press control-1:

document.body.addEventListener('keydown', (event) => {
  // keyCode 49 corresponds to the "1" key
  if(event.keyCode==49 && event.ctrlKey) {
    event.preventDefault();
    console.log('default action prevented, doing custom action instead');
  }
});

body {
  background-color: yellow;
}

click me first

根据需要重复任意数量的keyCode和修饰符.

Repeat for as many keyCodes and modifiers as you want.

这篇关于Google表格如何覆盖浏览器快捷方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆