解决onKeypress中文输入不触发问题

onKeypress事件会在键盘按键被按下并释放一个键时发生。在对input文本绑定时,输入数字、字母、特殊符号是都会触发onKeypress事件,但唯独输入中文时,onKeypress事件是不会触发的!我觉得可以使用onInput事件代替!

oninput 是 HTML5 的标准事件,对于检测 textarea, input:text, input:password 和 input:search 这几个元素通过用户界面发生的内容变化非常有用,在内容修改后立即被触发,不像 onchange 事件需要失去焦点才触发。oninput 事件在主流浏览器的兼容情况如下:

《解决onKeypress中文输入不触发问题》

有一个需求是这样的:在input框只能输入数字,能兼容火狐,IE9的。

如果是使用onKepress事件绑定input,输入中文时就会出现不触发onKeypress事件,也就是没有任何的意义!

演示地址 ==> http://runjs.cn/detail/pfojehd8

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>RunJS</title>
        <script>
            // scripts
            $(function() {
                // 给含有number属性的input控件绑定input事件
                // 这样以后要用的时候,就给input添加一个number属性就可以!
                $('body').detelage('input[number]:not(:hidden)', 'input', function() {
                    var $this = $(this), 
                        val = $this.val();
                    if (val) $this.val(val.replace(/[^0-9]/g, ''));
                });
            });
        </script>
    </head>
    <body>
        <!-- 给input 添加number属性 -->
        <input type="text" number />
    </body>
    </body>
</html>
    原文作者:Lazy
    原文地址: https://segmentfault.com/a/1190000008820968
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞