zoukankan      html  css  js  c++  java
  • 监听输入框值变化的最佳方案 oninput 和 onpropertychange (实时监控文本框改变的最佳方案)

    公司有个文本框,当输入文字/粘贴/复制 或者是键盘猛按的时候,都希望这个文本框能统计出 输入了多少字

     

    这种用 onchange   onkeyup  onkepress  都不怎么好使

     

    最后在快要无语的情况下,使用了  下面的组合方式

     onkeyup="commMaxLength(this,30,'leftWordTitle')" oninput="commMaxLength(this,30,'leftWordTitle')" onpropertychange="commMaxLength(this,30,'leftWordTitle')"

    有前辈说用jquery更风骚,于是下面发一个jquery的  (只写了 oninput  和 onpropertychange )

     

    $('textarea').bind('input propertychange', function() {
        $('.msg').html($(this).val().length + ' characters');
    });

    如果不用jquery库,还可以这样

    <head>
        <script type="text/javascript">
        // Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9
            function OnInput (event) {
                alert ("The new content: " + event.target.value);
            }
        // Internet Explorer
            function OnPropChanged (event) {
                if (event.propertyName.toLowerCase () == "value") {
                    alert ("The new content: " + event.srcElement.value);
                }
            } 
        </script>
    </head>
    <body>
        Please modify the contents of the text field.
        <input type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" value="Text field" />
    </body>


    最后是注释

    1、onchange事件与onpropertychange事件的区别:
    onchange事件在内容改变(两次内容有可能还是相等的)且失去焦点时触发;onpropertychange事件却是实时触发,即每增加或删除一个字符就会触发,通过js改变也会触发该事件,但是该事件IE专有。
    2、oninput事件与onpropertychange事件的区别:
    oninput事件是IE之外的大多数浏览器支持的事件,在value改变时触发,实时的,即每增加或删除一个字符就会触发,然而通过js改变value时,却不会触发;onpropertychange事件是任何属性改变都会触发的,而oninput却只在value改变时触发,oninput要通过addEventListener()来注册,onpropertychange注册方式跟一般事件一样。(此处都是指在js中动态绑定事件,以实现内容与行为分离)
    3、oninput与onpropertychange失效的情况:
    (1)oninput事件:a). 当脚本中改变value时,不会触发;b). 从浏览器的自动下拉提示中选取时,不会触发。
    (2)onpropertychange事件:当input设置为disable=true后,onpropertychange不会触发。

     

    知识链接 :http://www.zlovezl.cn/articles/12/

     

    最牛叉的解决方法(真的是实时的,可以着重看看这个) http://polaris.blog.51cto.com/1146394/265667/

  • 相关阅读:
    ajax01
    django04
    数据库
    WeakHashMap类
    IdentityHashMap
    Hashtable类
    LinkedHashMap类
    HashMap和TreeMap类
    PriorityQueue
    Synchronized
  • 原文地址:https://www.cnblogs.com/joeylee/p/3792904.html
Copyright © 2011-2022 走看看