试图防止从Mac键盘键入死键

问题描述 投票:0回答:3

我正在尝试使用组合键[[alt + i创建快捷方式,该组合通常会键入一个死键ˆ,我尝试了以下操作:

$(document).ready(function () { $("#txtInput").keydown( function (event) { if (event.which == 229 && event.altKey === true) { alert(event); event.preventDefault(); event.stopPropagation(); } } ); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input id="txtInput" type="text" />
条件内的代码已执行,但在我的"#txtInput"中仍键入

ˆ

。是否可以防止键入此文本?
javascript jquery jquery-events
3个回答
1
投票
我会将键与实际字符进行比较,例如

$("#txtInput").keydown( function (event) { if (('Ii'.indexOf(String.fromCharCode(event.which)) >= 0) && event.altKey === true) { console.log('Here you go'); // Do stuff here event.preventDefault(); event.stopPropagation(); } } );


1
投票
仅与事件的键进行比较,如果它等于'i'。觉得对我来说是最自然的解决方案。

$('#txtInput').keydown(function(e){ if( e.altKey && e.key == 'i'){ e.preventDefault(); console.log("Blocked"); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="txtInput">

0
投票
这是非常特定于键盘布局的,这可能不是通用的解决方案,但是您可以执行以下操作以使ALT + I快捷工作:

function custom() { console.log('The short-cut executed'); } let isDead = false; document.addEventListener('keydown', e => { if (e.altKey && e.code === 'KeyI') { custom(); }; if (isDead) { e.preventDefault(); } isDead = (e.key === 'Dead'); });
<input>
死键本身无法防止,但是死键之后产生的字符。由于现在不赞成使用键盘事件的许多属性,因此代码使用了相对较新的code property,它将提供所命中的物理键的代码。
© www.soinside.com 2019 - 2024. All rights reserved.