Events that are convenient to implement this function are displayed on the Internet:
Onpropertychange in IE
Oninput in non-IE
The advantage of using these two events is that when the content in the input box changes, the events related to using the key and mouse will be more complex, and this method is as effective as pasting. However, using js to change the value of input does not result in these two events.
Add two event methods in the text box. (We can see that the oninput method in non-ie should be bound with addEventListener and element. oninput = function (){...} no, but I can do it in Firefox 6. But for safety, here I still use the standard method element. addEventListener ('input', function (){...}) implementation)
Use the element. attachEvent ('onpropertychang', function () {...}) method in IE. However, in ie, all attributes are determined to change, which may cause a lot of unnecessary work and sometimes cause problems and the function cannot be called. So here I only judge when the value attribute changes (the propertyName attribute of the event object) and call the method. The result is:
Element. attachEvent ('onpropertychang', function () {if (window. event. propertyName = "value "){...})
Copy codeThe Code is as follows:
/*
Parameters:
Length: Maximum length
Ele: Input object
CallBack: callBack method. The len parameter indicates the number of bytes in the current input box. this In the method points to
AutoFire: automatically called once upon initial Activation
*/
Function input_max (length, ele, showEle, callBack, autoFire ){
If (ele. addEventListener ){
Ele. addEventListener ('input', change, false );
} Else {
Ele. attachEvent ('onpropertychang', 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 ()};
};
// 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 '> exceeds" +-len + "</span> ";
This. style. backgroundColor = "# FFC ";
This. style. borderColor = "# F00 ";
}
}
// Dynamic title
Input_max (30, document. getElementById ('news _ title'), document. getElementById ('news _ title_limit '), input_max_callBack, true );