On the Internet to see the event is very convenient to achieve this feature:
The Onpropertychange
in
IE
Oninput
in non-IE
The advantage of these two events is that when the contents of the input box are changed to invoke events, the associated events using key and mouse are more complex, and this method is as effective as the Paste method. However, using JS to change the value of input does not occur in these two events.
the method of adding two events to the text box in. (see the Internet said that non-ie in the Oninput method to use AddEventListener binding, with element.oninput = function () {...} No, but I can do it in Firefox 6, but for security reasons, I'm still using the standard method Element.addeventlistener (' Input ', function () {...}) Implementation)
uses element.attachevent (' Onpropertychange ', function () {...}) in IE Method. However, because IE will judge all the properties change, this will occur a lot of unnecessary work, and sometimes there are problems, can not call the function. So here I'm just going to judge when the value attribute changes (the PropertyName property of the event object) and call the method. The result:
element.attachevent (' Onpropertychange ', function () {if (Window.event.propertyName = = "value") {...})
Copy Code code as follows:
/*
Parameter:
Length: Maximum length
Ele: Input Object
CallBack: Callback method, parameter Len indicates current loss The number of bytes in the contents of the box, this in the method points to Ele
Autofire: First-time automatic invocation of
/
function Input_max (length, ele, Showele, Callback,autofir E) {
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))
};
//Automatic call once
if (autofire) {change ()};
}; The
//callback function
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 ' > over" +-len + "</span>";
This.style.backgroundColor = "#FFC";
This.style.borderColor = "#F00";
}
//Dynamic caption
Input_max (' News_title '), document.getElementById (' News_title _limit '), input_max_callback,true);