我正在使用箭头键(和A,W,D)在页面之间导航。
如何禁用textareas和inputfields的keydown函数?
$(document).keydown(function(e) { switch(e.which) { case 65: leftArrowPressed(); break; case 37: leftArrowPressed(); break; case 68: rightArrowPressed(); break; case 39: rightArrowPressed(); break; case 72: homePressed(); break; case 87: homePressed(); break; } });
答案 0 :(得分:0)
$(document).keydown(function (e) {
var element = e.target.nodeName.toLowerCase();
if ((element != 'input' && element != 'textarea') || $(e.target).attr("readonly") || (e.target.getAttribute("type") ==="checkbox")) {
if (e.keyCode === 8) {
return false;
}
}
});
答案 1 :(得分:0)
你可以使用它(需要Internet Explorer 9 +):
function leftArrowPressed() { console.log('left pressed'); }
function rightArrowPressed() { console.log('right pressed'); }
function homePressed() { console.log('home pressed'); }
$(document).keydown(function(e) {
var el = document.activeElement;
try {
if (el && el.selectionStart !== undefined || el.isContentEditable) {
console.log('skip');
return; // active element has caret, do not proceed
}
} catch (ex) {}
var f = {
65: leftArrowPressed,
37: leftArrowPressed,
68: rightArrowPressed,
39: rightArrowPressed,
72: homePressed,
87: homePressed
};
if (f[e.which]) f[e.which]();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input value="test">
<input type="checkbox">
<textarea>test
</textarea>
<div contenteditable>test</div>
答案 2 :(得分:0)
因为你正在使用jQuery:
$("input, textarea").on("keydown keyup",function(e){e.stopPropagation();});
...就是你需要的所有(代码片段中的其余代码不重要,仅用于概念验证)
$("input, textarea").on("keydown keyup",function(e){e.stopPropagation();});
$(document).keydown(function(e){console.log("key pressed: "+e.which);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="Test input" /> <textarea style="height:18px;">Test textarea</textarea> <div style="display:inline; border: 1px solid black;">Test div</div>
<div>1. Just click somewhere in the results area and start typing. Watch the console.<br />2. Then click inside the input/textarea and do the same. Nothing will happen.</div>