很久以前的文章了 迁徙至此
全兼容版javascript字符计数textarea, javascript字符计数textarea,空话不多说直接上代码,亲测好使,兼容一切浏览器。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>及时盘算input字符数目</title>
</head>
<body>
<input type="text" id="text" name="name" value="">
<div id="box">
</div>
<script type="text/javascript">
window.onload = function() {
var oT = document.getElementById('text');
var textBox = document.getElementById('box');
//参数 DOM 回调
getLength(oT, function(len){
textBox.innerHTML = len;
});
function getLength(obj,fn){
//如果是ie
if (navigator.userAgent.indexOf("MSIE") != -1) {
if (navigator.userAgent.indexOf("MSIE 9.0") != -1) {
obj.onpropertychange = function() {
fn(currentLen(obj.value));
};
} else {
obj.onfocus = function() {
timer = setInterval(function() {
fn(currentLen(obj.value));
}, 30);
};
obj.onblur = function() {
clearInterval(timer);
};
}
//其他浏览器直接oninput
} else {
obj.oninput = function() {
fn(currentLen(obj.value));
};
}
}
function currentLen(value) {
return value.replace(/[\u4E00-\u9FA50]/g, '..').length;
}
};
</script>
</body>
</html>
你的点赞是我继承的动力!
迎接多多吐槽斧正!感谢!