Tom Blog

Textarea 计数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!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){
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>