目前在用编辑器simditor,现在的一个需求是要给这个编辑器加一个字数限制。
能实时获取到当前编辑器内的value,例如:
<p style="font-size=14px">123456</p>
假如我限制五个字数的话,截断之后应为:
<p style="font-size=14px">12345</p>
统计字数很简单,只需要过滤掉标签,然后看过滤后的文本的长度就可以了。
但是在截断带有标签文本就犯难了,我该怎样准确又快捷的找到应该截断的位置呢?
曾经想到过一种取捷径的方法。就是在每次编辑器内值改变的时候(onValueChange)与改变之前的值(currentValue)进行对比,如果有更改之后,就进行正则去掉标签计算长度,若超过长度则将原来的值(currentValue)重新赋值给编辑器。
但是这个捷径在后来遇到了很多坑…… 首先他如果粘贴文字到超过限制字数的话,这段文字是粘不上的。我目前已经没有除了截取对应位置之后文字之外其他的方法。恳请各位大佬帮帮忙
var editorValue = editor.getValue();
var actualText_num = editorValue.replace(/<\/?[^>]*>/g,'').replace(/[ | ]*\n/g,'\n').replace(/\n[\s| | ]*\r/g,'\n').replace(/ /ig,'').length;
editor.on('valuechanged', function(e, type) {
var tmp_editorValue = editor.getValue();
if(tmp_editorValue === editorValue){
return;
}
var tmp_actualText = tmp_editorValue.replace(/<\/?[^>]*>/g,'').replace(/[ | ]*\n/g,'\n').replace(/\n[\s| | ]*\r/g,'\n').replace(/ /ig,'');
if(tmp_actualText.length > 50 && tmp_actualText.length >= actualText_num ){
editor.setValue(editorValue);
editor.focus();
}else{
editorValue = tmp_editorValue;
actualText_num = tmp_actualText.length;
}
…… 按照一楼的提示我查了一下uEditor的maximumWords,发现在官网的演示上,他只是在右下角提示了字数统计,在超过限制的时候给了一个警告…… 并没有截断这个操作。再次陷入尴尬
我帮你看了一下API,没有禁止输入的方法!
我说一下我的思路,不一定可行,我看到有个valuechanged事件,取巧一点的做法是在事件里面调用getValue()方法获取内容,判断内容长度并调用blur()方法,禁止再输入。
这是API:http://simditor.tower.im/docs...