在输入文本框中防止退格 [英] Prevent backspace in input text box

查看:98
本文介绍了在输入文本框中防止退格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个测试打字速度的Web应用程序.

I'm making a Web application that tests typing speeds.

它为用户提供了一些要键入的文本和一个输入框.如果用户键入了错误的键,那么我将在产生的键事件上使用preventDefault,以防止在输入框中输入错误的字符(而是向用户显示错误消息).

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).

问题是,preventDefault不会阻止输入退格键.理想情况下,由于永远不会在文本框中输入错误的按键操作,因此不允许使用退格键.如果用户习惯性地在感知到的错误上按了退格键,则会导致输入框中的文本变得不正确.这不会影响测试结果,这只是一个不理想的情况.

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.

如何防止类型为文本"的HTML5输入元素中的退格?

How can I prevent backspacing in HTML5 input elements of type "text"?

推荐答案

您需要检测onkeydown而不是onkeypress,它应该可以工作(已在Firefox/Safari上测试).在某些浏览器中,onkeypress仅限可打印字符,而onkeydown则适用于所有按键事件.

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>

这篇关于在输入文本框中防止退格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆