我尝试将其用于一个简单的热键功能,它对某些键的按键使用react,但如果您在具有给定 ID 的框中进行编辑则不会。不幸的是,现在热键总是被禁用。我一直收到 alert() :(
文本框在例如http://tyrant.40in.net/kg/news.php?id=160#comments
在文本区域内它可以工作,但我的脚本无法识别,无论我是在文本区域内还是在文本区域外(在文本区域内单击并在外部单击也无济于事)。
请帮帮我。
我还尝试通过选择 (!$('#tfta_1 #search')) 而不是 $('html') 来以另一种方式进行操作,这样当您位于这些 ID 中时,热键就不起作用。不幸的是,这对以太币不起作用。
编辑:js 还必须检查是否 crtl、alt、shift 以避免解释
// Hotkeys (listen to keyboard input)
$('html').keypress(
function(event){
// is cursor at the beginning / end of edit box
var textInput = document.getElementById("tfta_1"), val = textInput.value;
var isAtStart = false, isAtEnd = false;
if (typeof textInput.selectionStart == "number") {
// Non-IE browsers
isAtStart = (textInput.selectionStart == 0);
isAtEnd = (textInput.selectionEnd == val.length);
} else if (document.selection && document.selection.createRange) {
// IE branch
textInput.focus();
var selRange = document.selection.createRange();
var inputRange = textInput.createTextRange();
var inputSelRange = inputRange.duplicate();
inputSelRange.moveToBookmark(selRange.getBookmark());
isAtStart = inputSelRange.compareEndPoints("StartToStart", inputRange) == 0;
isAtEnd = inputSelRange.compareEndPoints("EndToEnd", inputRange) == 0;
}
// combine information -> is cursor in edit box?
var eb = isAtStart + isAtEnd;
// if in comment box
if ( eb ) {
// do nothing
alert('You are in the comment box');
}
// if key 'p' is pressed
else if (event.which == 112){
// open profile page
window.location = home + 'profile.php';
}
// if key 'q' is pressed
else if (event.which == 113){
// open quests overview
window.location = home + 'quests.php';
}
// if key 'r' is pressed
else if (event.which == 114){
// open raids overview
window.location = home + 'raids.php';
}
// if key 'f' is pressed
else if (event.which == 102){
// open fraction tracker
window.location = home + 'factiontracker.php';
}
}
);
最佳答案
您需要检查 event.target
属性(property)。
if ('textarea' == event.target.tagName.toLowerCase()) {
return;
}
或者:
if ($(event.target).is('textarea')) {
return;
}
至于修改键,请参阅 event.shiftKey , event.ctrlKey和 event.altKey .
关于javascript - 通过 JS 添加热键,不包括 textarea/input 内的区域,并在按下 Ctrl、Alt 或 Shift 时跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13974151/