Javascript 如何禁用所有键盘键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10261325/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:32:51  来源:igfitidea点击:

How can I disable all keyboard keys?

javascript

提问by Philipp Braun

I am searching for a possibility to disable all keyboard keys in a textarea. I found some examples on the web to disable some single ones but how can I disable the whole keyboard??

我正在寻找禁用文本区域中所有键盘键的可能性。我在网上找到了一些示例来禁用某些单个键盘,但如何禁用整个键盘?

回答by Robert Kajic

You can disable the textarea using the disabled attribute. Or you can make it read only using the readonly attribute. readonly is like disabled except it doesn't prevent the user from clicking or selecting in the textarea.

您可以使用disabled 属性禁用 textarea 。或者您可以使用 readonly 属性使其只读。readonly 就像 disabled ,但它不会阻止用户在 textarea 中单击或选择。

And if you really need to do it with javascript something like this will do it (using jQuery):

如果你真的需要用 javascript 来做,像这样可以做到(使用 jQuery):

<textarea rows=3 cols=20></textarea>?

$("textarea").keydown(false);

You can try it here: http://jsfiddle.net/7n4G4/1/

你可以在这里试试:http: //jsfiddle.net/7n4G4/1/

回答by Tobias Krogh

use the readonly attribute if you want to make sure that your user can still click and select inside of the textarea

如果您想确保您的用户仍然可以在 textarea 内单击和选择,请使用 readonly 属性

<textarea name="text" readonly>

if you want to keep it completely disabled without selecting

如果你想在不选择的情况下完全禁用它

<textarea name="text" disabled>

if want to prevent only keyboard input

如果只想防止键盘输入

<textarea name="text" id="text-input">

very simple with jQuery

使用 jQuery 非常简单

$("#text-input").on("keydown keypress keyup", false);

回答by ZER0

Assuming you have in textarethe reference of your textarea, maybe something like:

假设你有你textare的参考textarea,也许是这样的:

textearea.onkeydown = textarea.onkeypress = function() { return false };

That it's probably an overkill, but... Considering to use the attribute readonly instead:

这可能是一种矫枉过正,但是......考虑使用属性 readonly 代替:

textarea.readOnly = true

In the first case you're still able to copy/paste using the mouse, in the second case you can only copy (using keys or mouse doesn't matter).

在第一种情况下,您仍然可以使用鼠标复制/粘贴,在第二种情况下,您只能复制(使用键或鼠标无关紧要)。

回答by Manishearth

 document.getElementById('ID OF TEXTAREA').onkeypress=function(){return false;}

Dunno why you want to do that if you can just disabledit.

如果可以的话,不知道为什么要这样做disabled