js 实现maxlength
使用 maxlength 属性
HTML 的 input 或 textarea 元素可以直接通过 maxlength 属性限制输入长度:
<input type="text" maxlength="10">
<textarea maxlength="50"></textarea>
通过 JavaScript 动态限制
通过事件监听实现更灵活的校验,例如实时显示剩余字数:
const input = document.querySelector('input');
const maxLength = 10;
input.addEventListener('input', () => {
if (input.value.length > maxLength) {
input.value = input.value.slice(0, maxLength);
}
});
结合提示功能
在限制输入的同时显示剩余字数:
<input type="text" id="limited-input">
<span id="counter"></span>
const input = document.getElementById('limited-input');
const counter = document.getElementById('counter');
const maxLength = 20;
input.addEventListener('input', () => {
const remaining = maxLength - input.value.length;
counter.textContent = `${remaining} characters left`;
if (remaining <= 0) {
input.value = input.value.slice(0, maxLength);
counter.style.color = 'red';
} else {
counter.style.color = 'black';
}
});
处理粘贴行为
拦截粘贴内容并自动截断:
input.addEventListener('paste', (e) => {
e.preventDefault();
const pastedText = e.clipboardData.getData('text').slice(0, maxLength);
const newValue = input.value + pastedText;
input.value = newValue.slice(0, maxLength);
});
兼容非输入框元素
对于 contenteditable 的 DIV 元素实现类似效果:
const editableDiv = document.querySelector('[contenteditable]');
editableDiv.addEventListener('keydown', (e) => {
if (editableDiv.textContent.length >= 30 && e.key !== 'Backspace') {
e.preventDefault();
}
});






