Javascript 内容可编辑字数,包括默认文本

Javascript 内容可编辑字数,包括默认文本,javascript,css,Javascript,Css,我有这个: document.getElementById('editor').addEventListener('input',function(){ var countThis=this.textContent, count=countThis.trim().replace(/\s+/g'').split('').length; document.querySelector('.words').textContent=count; }); #编辑器{背景:silver;大纲:0;} .wo

我有这个:

document.getElementById('editor').addEventListener('input',function(){
var countThis=this.textContent,
count=countThis.trim().replace(/\s+/g'').split('').length;
document.querySelector('.words').textContent=count;
});
#编辑器{背景:silver;大纲:0;}
.words{background:aqua;}

默认文本。。。

只需创建一个可重用的函数:

var editor=document.getElementById('editor');
var words=document.querySelector('.words');
函数wordscont(){
var content=editor.textContent.trim(),
计数=内容。替换(/\s+/g')。拆分(“”)。长度;
words.textContent=计数;
}
editor.addEventListener('input',wordsCount);
wordscont()
#编辑器{背景:silver;大纲:0;}
.words{background:aqua;}

默认文本。。。

太完美了。非常感谢。