javascript 如何在javascript中禁用输入文本框上的键盘事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18660002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to disable keyboard events on an input text box in javascript
提问by user1499220
I have an image, and I use keyboards to apply some manipulations on it (translation, zoom ..). Above the image, I have an input text box which shows the number of the image in the data set. How can I disable the image manipulation when the cursor is on the text box? (ie disable the behavior that I assigned to each keyboard). I would also like to still be able to edit the text box(to move to image number xx for example). From what I read here IPad Disable keyevent on input, I think the solution would be something like this:
我有一个图像,我使用键盘对其进行一些操作(翻译、缩放 ..)。在图像上方,我有一个输入文本框,显示数据集中图像的编号。当光标位于文本框上时,如何禁用图像操作?(即禁用我分配给每个键盘的行为)。我还希望仍然能够编辑文本框(例如移动到图像编号 xx)。从我在这里读到的IPad Disable keyevent on input,我认为解决方案是这样的:
// input text field
var currentPosDisplay = $('<input type=text id="currentPos" onkeypress="return disableManipulation();" value="1" style="display:inline" >');
But I don't know how to implement disableManipulation() so that when I press on a key board (inside the text box), only the default behavior occurs (and not the image manipulation)
但我不知道如何实现 disableManipulation() 以便当我按下键盘(在文本框内)时,只会发生默认行为(而不是图像操作)
回答by T.J. Crowder
It sounds like you want to let the user change the value in the input
, but you don't want those events to be seen at the document (or some other container) level, where you've hooked the keyboard events for image manipulation.
听起来您想让用户更改 中的值input
,但您不希望在文档(或其他容器)级别看到这些事件,在那里您已将键盘事件挂钩以进行图像操作。
If that's the case, you can do that with Event#stopPropagation
:
如果是这种情况,您可以使用以下方法Event#stopPropagation
:
var currentPosDisplay = $('<input type=text id="currentPos" value="1" style="display:inline" >');
currentPosDisplay.on("keypress keydown keyup", function(e) {
e.stopPropagation();
});
回答by jozxyqk
You could check if the input element has focus: How do I find out which DOM element has the focus?
您可以检查输入元素是否具有焦点:如何找出哪个 DOM 元素具有焦点?
And if it does, don't apply your image manipulation.
如果是这样,请不要应用您的图像处理。
Returning false from the onkeypress handler will ignore the key that was pressed, but if you have focus it sounds like you don't want that anyway.
从 onkeypress 处理程序返回 false 将忽略按下的键,但如果你有焦点,听起来你不想要那样。