一:需求描述
在浏览页面时。我们可能会看到一些评论的盒子,它里边会有一个字数限制,并在我们输入字时提示我们已经输入几个字。这样的用户体验也比较好。
二:解决方法
//内容
<textarea id="comment_content" placeholder="说点什么吧..."></textarea>
<span class="Comment_word_count float_right">0/300</span>
<script>
let Comment_word_count = document.getElementsByClassName("Comment_word_count")[0]//获取评论框显示字数的元素
let comment_content = document.getElementById("comment_content")//获取评论的字数
// 键盘被按下显示字数的盒子改变(oninput可以解决长按键盘时字数不更新的情况)
document.oninput = function () {
console.log(comment_content.value.length)
// 换行符不算
comment_content.value = comment_content.value.replace(/\n|\r/gi, "")
Comment_word_count.innerHTML = (comment_content.value.length) + "/300"
}
</script>
三:说明
第一印象我们肯定是想到键盘的onmouseup和onmousedown方法,这是可以的但是会出现一个bug就是在长按键盘时不会记录字数只在按下或松开时才记录。