可信的字数包括默认文本

问题描述 投票:1回答:1

我有这个:

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。

javascript css
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.