【发布时间】:2020-02-01 21:52:46
【问题描述】:
当字符数超过最大限制(20 个字符)时,substring 方法会返回输入中从索引 0 到 20 的字符。substring 方法会覆盖用户尝试键入超过 20 个字符数的所有内容。
但在我的程序中,我可以在达到最大限制后输入更多字符。为什么会这样?我不希望这种情况发生。
const txt = document.querySelector('textarea')
const message = document.querySelector('.message')
let maxLength = 20;
let warnLength = 15;
['keyup', 'keydown', 'change'].forEach(event => {
txt.addEventListener(event, textCounter)
})
function textCounter() {
let count = txt.value.length
if (count > warnLength) {
message.innerHTML = `${(maxLength-count)} characters left`
} else if (count > maxLength) {
txt.value = txt.value.substring(0, maxLength)
}
}
textarea {
width: 400 px;
height: 100 px;
}
<textarea></textarea>
<div class="message"></div>
【问题讨论】:
标签: javascript html character counting