同时绑定onpropertychange 和 oninput 事件,实时检测 input、textarea输入改变事件,支持低版本IE,支持复制粘贴

实时检测 input、textarea输入改变事件,支持低版本IE,支持复制粘贴

检测input、textarea输入改变事件有以下几种:

1、onkeyup/onkeydown 捕获用户键盘输入事件。
  缺陷:复制粘贴时无法检测
2、onchenge
  缺陷:要满足触发条件:当前对象的属性改变(由键盘或鼠标触发)且对象失去焦点
3、onpropertychange 当前对象属性改变就会触发
  缺陷:只支持低版本IE
4、oninput 和onpropertychange类似,当前对象属性改变就会触发
  缺陷:不支持低版本IE
 
可以看出以上几种方法都有各自的缺陷,1和2一般不能满足需求,3和4的缺陷正好互补,两个事件结合起来使用可以兼容IE、firefox、chrome;
 
所以同时绑定onpropertychange 和 oninput 可以达到实时检测输入内容的目的
(jquery用propertychange 和 input)。
代码实例(jquery):
<!--superGG1990原创发表于博客园http://www.cnblogs.com/superGG1990,其他商业网站转载均为盗版,个人博客网站转载请注明出处 2017-05-12-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>监听输入事件</title>
    <script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
    <style>
        b {color:red; font-size:18px;}
    </style>
</head>
<body>
    <textarea style="800px; height:300px;"></textarea>
    <div>你已经输入了<b>0</b>个字</div>
    <script>
        $('textarea').on('input propertychange',function(){
            var val = $(this).val()
            var textNum = val.length;
            if(textNum > 200){
                textNum = 200;
            }
            $('b').html(textNum)
            //超过200个字提示
            if(val.length>200){
                var textVal = val.substring(0,200)
                $(this).val(textVal)
                alert('评论内容大于200字')
            }
        })
    </script>
</body>
</html>

原文出处 superGG1990  www.cnblogs.com/superGG1990

原文地址:https://www.cnblogs.com/baiyangyuanzi/p/6856598.html