想实现的效果类似于 input的maxlength属性。
<input maxlength='10'/>
此方式存在问题:
- 复制粘贴依然无法限制
- 输入超限制后会失焦,但input框不会
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style>
div {
width: 300px;
height: 300px;
background-color: blanchedalmond;
border: 1px salmon solid;
}
</style>
<body>
<div contenteditable="true"></div>
<script>
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");
}
}
</script>
</body>
</html>
网友评论