检测键盘布局是否导致修饰符碰撞



我最近收到一个来自瑞典客户的bug投诉,他的Mac键盘默认布局是Option+2产生@标志。客户告诉我芬兰所有的键盘都是这样的布局。

据我所知,美国QWERTY布局或英国QWERTY布局的键盘有Shift+2来制作@标志。问题在于我在网站上有一个快捷设置,使用选项+2来执行导航。这将迫使瑞典/芬兰的任何用户在他们想要输入@标志时进行导航。

是否有一种方法可以事先知道用户正在使用的键盘布局有"不是我期望的修饰符"?或者我必须为他们提供禁用导航的选项吗?我现在检测键的方式(在Angular中):

@HostListener('document:keydown', ['$event'])
public onPublicKeyDown(event: KeyboardEvent) {
if (event.altKey) {
switch (event.code) {
case 'Digit2':
// Perform the navigation
}
}
}

考虑到各种操作系统的可用性和兼容性,我建议将Alt更改为Ctrl(即Ctrl+2)。

然而,也有一种JS方法来检查用户是否试图在文本字段中输入文本。

事件从处于焦点的元素向上和向下冒泡到等待处理的顶层元素(BODY)。

很容易检查事件是否达到了目标:

// check that event was not picked by inputs and bubbled up
// to the element to which it was attached (i.e. document.body)
if (event.currentTarget === event.target) {
...
}

事件。currentttarget指的是事件处理程序附加到的元素(我假设onPublicKeyDown事件处理程序附加到页面的BODY)

事件。target是指事件被分派到的对象(当焦点在INPUT元素中并且用户在字段中输入文本时,它将是INPUT,如果焦点不在INPUT元素中,它可能是页面的BODY。

下面是工作示例:

function onPublicKeyDown(event) {
// check that event was not picked by inputs and bubbled up
// to the element to which it was attached (i.e. document.body)
if (event.target === event.currentTarget) {
if (event.altKey) {
switch (event.code) {
case 'Digit2':
// Perform the navigation
alert('Navigating away...');
}
}
}
}
document.body.addEventListener('keydown', onPublicKeyDown);
Try press 'option + 2' when focused inside input and when outside.<br>
<input type="text" />

最新更新