问题
I'm making a Web application that tests typing speeds.
It gives the user some text to type, and an input box to type into. If the user types a wrong key, I'm using preventDefault
on the produced key event to prevent the wrong character from being entered into the input box (I instead show the user an error message).
The problem is, preventDefault
doesn't prevent backspaces from being entered. Ideally, since wrong keys presses will never be entered into the text box, it doesn't make sense to allow backspacing. If the user habitually hits backspace on a perceived error, it causes the text in the input box become incorrect. This doesn't affect the results of the test, it's just not an ideal situation.
How can I prevent backspacing in HTML5 input elements of type "text"?
回答1:
You need to detect onkeydown instead of onkeypress and it should work (tested on Firefox/Safari). On some browsers onkeypress is limited to printable characters, whereas onkeydown is for all key down events.
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript">
function no_backspaces(event)
{
backspace = 8;
if (event.keyCode == backspace) event.preventDefault();
}
</script>
</head>
<body>
<input id="typeHere" onkeydown="no_backspaces(event);"/>
</body>
</html>
来源:https://stackoverflow.com/questions/35869026/prevent-backspace-in-input-text-box