首页 / 脚本样式 / JavaScript / 输入框的字数时时统计—关于 onpropertychange 和 oninput 使用
网上看到很方便实现这个功能的事件:
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);