使用onkeyup事件监听输入框内容长度,并显示在页面
- 效果展示
2. 代码展示
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>输入文本</title>
</head>
<body>
<p>字数限制在30字内,<span><span id="be">您还可以输入</span><b id='num'>30</b>字</span></p>
<textarea cols="50" rows="7" id="text"></textarea>
<script type="text/javascript">
//补充代码
var text = document.getElementById('text');
var num = document.getElementById('num');
var be = document.getElementById('be');
text.onkeyup = function(){
var val = text.value;
var len = val.length;
num.innerHTML = 30-len;
if(num.innerHTML<=0){
num.innerHTML = len-30;
be.innerHTML = '您已超出';
}else{
num.innerHTML = 30-len;
be.innerHTML = '您还可以输入';
}
}
</script>
</body>
</html>