请用js写一个文本输入框,输入文字后显示清除控件可以删除所有文字,限制文字字数,字数超出会在底部有红色提示。输入时显示字数统计。
时间: 2024-04-30 19:22:39 浏览: 15
好的,以下是用JS实现的文本输入框代码:
HTML代码:
```html
<div>
<textarea id="input" placeholder="请输入文字"></textarea>
<span id="tip" style="color: red;"></span>
<span id="count"></span>
<button id="clear" style="display: none;">清空</button>
</div>
```
JS代码:
```javascript
var input = document.getElementById('input');
var tip = document.getElementById('tip');
var count = document.getElementById('count');
var clear = document.getElementById('clear');
var maxLength = 20; // 最大字数
// 输入时显示字数统计
input.addEventListener('input', function() {
var len = input.value.length;
count.innerText = len + '/' + maxLength;
if (len > maxLength) {
tip.innerText = '字数超过限制!';
tip.style.display = 'inline';
clear.style.display = 'inline';
input.style.borderColor = 'red';
} else {
tip.style.display = 'none';
clear.style.display = 'none';
input.style.borderColor = '#ccc';
}
});
// 点击清空按钮
clear.addEventListener('click', function() {
input.value = '';
count.innerText = '0/' + maxLength;
tip.style.display = 'none';
clear.style.display = 'none';
input.style.borderColor = '#ccc';
});
```
使用时,将以上HTML代码和JS代码分别放入HTML和JS文件中,并在HTML文件中引入JS文件即可。