我有这个:
document.getElementById('editor').addEventListener('input', function () {
var countThis = this.textContent,
count = countThis.trim().replace(/\s+/g, ' ').split(' ').length;
document.querySelector('.words').textContent = count;
});

#editor {background: silver; outline: 0;}
.words {background:aqua;}

<main id="editor" contenteditable="true">
Default text...
</main>
<div class="words"></div>
&#13;
一旦我开始输入,脚本就会开始计数。但我希望它也可以在页面加载时计数,首先显示默认文本字数。有任何想法吗? 仅限Javascript。
答案 0 :(得分:3)
只需制作可重复使用的功能:
var editor = document.getElementById('editor');
var words = document.querySelector('.words');
function wordsCount () {
var content = editor.textContent.trim(),
count = content.replace(/\s+/g, ' ').split(' ').length;
words.textContent = count;
}
editor.addEventListener('input', wordsCount);
wordsCount();
#editor {background: silver; outline: 0;}
.words {background:aqua;}
<main id="editor" contenteditable="true">
Default text...
</main>
<div class="words"></div>
如果您删除所有文字,则可能还需要显示0
个字词!
var editor = document.getElementById('editor');
var words = document.querySelector('.words');
function wordsCount () {
var arr = editor.textContent.trim().replace(/\s+/g, ' ').split(' ');
words.textContent = !arr[0] ? 0 : arr.length;
}
editor.addEventListener('input', wordsCount);
wordsCount();
#editor {background: silver; outline: 0;}
.words {background:aqua;}
<main id="editor" contenteditable="true">
Default text...
</main>
<div class="words"></div>
要了解更多内容,请参阅:Word and character counter