html代码如下:
-
<div class="customer-message">
-
<label for="customerMessage">留言</label>
-
<textarea id="customerMessage" maxlength="500o"></textarea>
-
<p class="text-count"><span id="textCount">0</span>/500(留言多余10个字)</p>
-
</div>
js代码如下:
-
window.onload = function () {
-
//获取文本内容和长度函数
-
function txtCount(el) {
-
var val = el.value;
-
var eLen = val.length;
-
return eLen;
-
}
-
-
var el = document.getElementById('customerMessage');
-
el.addEventListener('input',function () {
-
var len = txtCount(this); // 调用函数
-
document.getElementById('textCount').innerHTML = len;
-
});
-
-
el.addEventListener('propertychange',function () {//兼容IE
-
var len = txtCount(this); // 调用函数
-
document.getElementById('textCount').innerHTML = len;
-
});
-
}
记录如上