作家
登录

输入框的字数时时统计—关于 onpropertychange 和 oninput 使用

作者: 来源:www.28hudong.com 2013-03-30 00:41:41 阅读 我要评论

网上看到很方便实现这个功能的事件: IE 中的 onpropertychange 非IE中的 oninput 用这两事件的好处是,当在输入框的内容发生变化调用事件,使用key 和 mouse的相关事件会比较复杂,而且这个方法用粘贴方法一样有效。 不过用js改变input的value值不会发生这两个事件。 在中文本框中添加两个事件的方法就可以了。(看到网上说非ie中的oninput方法要用addEventListener绑定,用 element.oninput = function(){...}不行,可是我在火狐6中是可以的,不过为了安全起见,这里我还是使用标准的方法 element.addEventListener('input',function(){...})实现 ) 在IE中 使用 element.attachEvent('onpropertychange', function(){...})方法。 不过,因为ie中会判断所有的属性发生变化,这样会发生很多不必要的工作,而且有时候会出现问题,无法调用函数。 所以这里我只对当value属性发生变化的时候进行判断(事件对象的propertyName属性),并调用方法。 结果是: element.attachEvent('onpropertychange', function(){if(window.event.propertyName == "value"){...}) 复制代码 代码如下: /* 参数: length:最大长度 ele: 输入对象 callBack: 回调方法,参数len表示当前输入框内容字节数, 方法中的this指向ele对 autoFire: 初使化自动调用一次 */ function input_max(length, ele, showEle, callBack,autoFire){ if(ele.addEventListener){ ele.addEventListener('input', change, false); }else{ ele.attachEvent('onpropertychange', function(){if(window.event.propertyName == "value"){alert('a');change()}}) } function change(){ var len = Math.ceil(byteLength(ele.value)/2); len = len <= length ? len : length - len; callBack.call(ele,showEle,len); }; function byteLength(b) { if (typeof b == "undefined") { return 0 } var a = b.match(/[^x00-x80]/g); return (b.length + (!a ? 0 : a.length)) }; //自动调用一次 if(autoFire){change()}; }; // 回调函数 function input_max_callBack(showEle,len){ var note = showEle; if (len >= 0 ){ note.innerHTML = len ; this.style.borderColor = ""; this.style.backgroundColor = ""; }else{ note.innerHTML = "<span class='red b fz_14'>超过" + -len + "</span>"; this.style.backgroundColor = "#FFC"; this.style.borderColor = "#F00"; } } // 动态标题 input_max(30, document.getElementById('news_title'), document.getElementById('news_title_limit'),input_max_callBack,true);

  推荐阅读

  javascript nextSibling 与 getNextElement(node) 使用介绍

1. nextSibing:下一个节点,节点类型可以是任何一种,其中就有文本节点。 2.得到下一个元素节点: 复制代码 代码如下: function getNextElement(node){ if(node.nodeType == 1){ return node; } if(node.nextSibl>>>详细阅读


本文标题:输入框的字数时时统计—关于 onpropertychange 和 oninput 使用

地址:http://www.17bianji.com/kaifa2/JS/24047.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)