很久以前的文章了 遷移至此
全兼容版javascript字符計數(shù)textarea饰潜, javascript字符計數(shù)textarea和簸,廢話不多說直接上代碼,親測好使薯酝,兼容所有瀏覽器爽柒。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>實時計算input字符數(shù)量</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');
//參數(shù) DOM 回調(diào)
getLength(oT, function(len){
textBox.innerHTML = len;
});
function getLength(obj,fn){
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);
};
}
} else {
obj.oninput = function() {
fn(currentLen(obj.value));
};
}
}
function currentLen(value) {
return value.replace(/[\u4E00-\u9FA50]/g, '..').length;
}
};
</script>
</body>
</html>