想实现的效果类似于 input的maxlength属性。
此方式存在问题:
复制粘贴依然无法限制
输入超限制后会失焦,但input框不会
Documentdiv {
width: 300px;
height: 300px;
background-color: blanchedalmond;
border: 1px salmon solid;
}
const editDiv = document.querySelector("div");
editDiv.addEventListener("keydown", (e) => {
limitTextLength(e);
});
editDiv.addEventListener('click',()=>{
editDiv.setAttribute("contenteditable", "true");
editDiv.focus()
})
function limitTextLength(e) {
let textLength = editDiv.innerText.length;
let allowKey = [8, 13, 37, 38, 39, 40]; // 上下左右 回车 删除
let maxLength = 5;
if (textLength >= maxLength && allowKey.indexOf(e.keyCode) === -1) {
editDiv.setAttribute("contenteditable", "false");
}
}