>我有这个:
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>
一旦我开始键入,脚本就会开始计数。但我希望它在加载页面时也计数,首先显示默认文本字数计数。有什么想法吗?请只做Javascript。
只需创建一个可重用的函数:
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>
要了解更多信息,请参阅: 字数和字符计数器