Javascript 限制 tinyMCE 中的字符数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11342921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limit the number of character in tinyMCE
提问by Rakesh Shetty
Im using tinyMCe
for my project.Everything is working fine but now i want to restrict the number of character that will be insert into tinyMce
textarea
我tinyMCe
用于我的项目。一切正常,但现在我想限制将插入到tinyMce
textarea的字符数
tinyMCE.init({
// General options
mode : "textareas",
theme : "simple",
plugins : "autolink,lists,pagebreak,style,table,save,advhr,advimage,advlink,emotions,media,noneditable,nonbreaking",
// Theme options
theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,fontselect,fontsizeselect",
theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,code,|,forecolor,backcolor",
theme_advanced_toolbar_location : "top",
theme_advanced_toolbar_align : "left",
theme_advanced_statusbar_location : "bottom",
max_chars : "10",
max_chars_indicator : "lengthBox",
theme_advanced_resizing : true
});
I used :-
我用了 :-
max_chars : "10",
max_chars_indicator : "lengthBox",
but still not working.Thanks in advance.
但仍然无法正常工作。提前致谢。
回答by needfulthing
This works in tinyMCE 4.3.12 and also captures pasting:
这适用于 tinyMCE 4.3.12 并捕获粘贴:
EDIT: Fixed bugs and extended code to display a character counter under the editor. Possibly not the best way as it relies a bit on the current HTML structure of tinyMCE having the editor div before the hidden textarea.
编辑:修复了在编辑器下显示字符计数器的错误和扩展代码。可能不是最好的方法,因为它有点依赖于 tinyMCE 的当前 HTML 结构,在隐藏的文本区域之前有编辑器 div。
This version only counts the text length and ignores HTML tag length. To count full HTML length, replace all "innerText" with "innerHTML".
此版本只计算文本长度,忽略 HTML 标签长度。要计算完整的 HTML 长度,请将所有“innerText”替换为“innerHTML”。
tinymce.init({
max_chars: 1000, // max. allowed chars
setup: function (ed) {
var allowedKeys = [8, 37, 38, 39, 40, 46]; // backspace, delete and cursor keys
ed.on('keydown', function (e) {
if (allowedKeys.indexOf(e.keyCode) != -1) return true;
if (tinymce_getContentLength() + 1 > this.settings.max_chars) {
e.preventDefault();
e.stopPropagation();
return false;
}
return true;
});
ed.on('keyup', function (e) {
tinymce_updateCharCounter(this, tinymce_getContentLength());
});
},
init_instance_callback: function () { // initialize counter div
$('#' + this.id).prev().append('<div class="char_count" style="text-align:right"></div>');
tinymce_updateCharCounter(this, tinymce_getContentLength());
},
paste_preprocess: function (plugin, args) {
var editor = tinymce.get(tinymce.activeEditor.id);
var len = editor.contentDocument.body.innerText.length;
var text = $(args.content).text();
if (len + text.length > editor.settings.max_chars) {
alert('Pasting this exceeds the maximum allowed number of ' + editor.settings.max_chars + ' characters.');
args.content = '';
} else {
tinymce_updateCharCounter(editor, len + text.length);
}
}
});
function tinymce_updateCharCounter(el, len) {
$('#' + el.id).prev().find('.char_count').text(len + '/' + el.settings.max_chars);
}
function tinymce_getContentLength() {
return tinymce.get(tinymce.activeEditor.id).contentDocument.body.innerText.length;
}
Reference: How can I prevent tinyMCE's paste event?
回答by Vladimir Miroshnichenko
TinyMCE 4+
+
jQuery
TinyMCE 4+
+
jQuery
<textarea id="description_edit" name="description_edit"><?=htmlspecialchars($this->company->description);?></textarea>
<div><span>Characters left:</span> <span id="chars_left"></span></div>
<script type="text/javascript" src="/js/tinymce/tinymce.min.js"></script>
<script>
var max_chars = 200; //max characters
var max_for_html = 300; //max characters for html tags
var allowed_keys = [8, 13, 16, 17, 18, 20, 33, 34, 35, 36, 37, 38, 39, 40, 46];
var chars_without_html = 0;
function alarmChars() {
if (chars_without_html > (max_chars - 25)) {
$('#chars_left').css('color', 'red');
} else {
$('#chars_left').css('color', 'gray');
}
}
$(function () {
tinymce.init({
selector: "#description_edit",
theme: "modern",
width: 320,
height: 130,
plugins: [
"advlist autolink lists charmap print preview hr anchor pagebreak",
"searchreplace visualblocks visualchars code insertdatetime media nonbreaking",
"save table contextmenu directionality paste textcolor"
],
image_advtab: true,
language: 'en',
menubar: false,
statusbar: false,
setup: function (ed) {
ed.on("KeyDown", function (ed, evt) {
chars_without_html = $.trim(tinyMCE.activeEditor.getContent().replace(/(<([^>]+)>)/ig, "")).length;
chars_with_html = tinyMCE.activeEditor.getContent().length;
var key = ed.keyCode;
$('#chars_left').html(max_chars - chars_without_html);
if (allowed_keys.indexOf(key) != -1) {
alarmChars();
return;
}
if (chars_with_html > (max_chars + max_for_html)) {
ed.stopPropagation();
ed.preventDefault();
} else if (chars_without_html > max_chars - 1 && key != 8 && key != 46) {
alert('Characters limit!');
ed.stopPropagation();
ed.preventDefault();
}
alarmChars();
});
},
toolbar: "bold italic underline | alignleft aligncenter alignright alignjustify | forecolor backcolor | bullist numlist | charmap",
style_formats: [
{title: 'Bold text', inline: 'b'},
{title: 'Red text', inline: 'span', styles: {color: '#ff0000'}},
{title: 'Red header', block: 'h1', styles: {color: '#ff0000'}},
{title: 'Example 1', inline: 'span', classes: 'example1'},
{title: 'Example 2', inline: 'span', classes: 'example2'},
{title: 'Table styles'},
{title: 'Table row 1', selector: 'tr', classes: 'tablerow1'}
]
});
chars_without_html = $.trim($("#description_edit").text().replace(/(<([^>]+)>)/ig, "")).length;
$('#chars_left').html(max_chars - chars_without_html);
alarmChars();
});
</script>
回答by Keen Wong
Answers above were great! I've made a small amendment so that we can set max_chars by adding it as an attribute to textarea element itself
楼上的回答太好了!我做了一个小的修改,以便我们可以通过将 max_chars 作为属性添加到 textarea 元素本身来设置它
setup : function(ed) {
ed.onKeyDown.add(function(ed, evt) {
//if ( $(ed.getBody()).text().length+1 > ed.getParam('max_chars')){
if ( $(ed.getBody()).text().length+1 > $(tinyMCE.get(tinyMCE.activeEditor.id).getElement()).attr('max_chars')){
evt.preventDefault();
evt.stopPropagation();
return false;
}
});
}
回答by a0z0ra
Providing support to backspace and delete keys. My version:
提供对退格键和删除键的支持。我的版本:
max_chars : 2000,
max_chars_indicator : ".maxCharsSpan",
setup : function(ed) {
wordcount = 0;
wordCounter = function (ed, e) {
text = ed.getContent().replace(/<[^>]*>/g, '').replace(/\s+/g, ' ');
text = text.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
this.wordcount = ed.getParam('max_chars') - text.length;
$(ed.getParam('max_chars_indicator')).text( this.wordcount + " (out of " +ed.getParam('max_chars')+ ") char(s) left." );
};
ed.onKeyUp.add( wordCounter );
ed.onKeyDown.add(function(ed, e) {
if (this.wordcount <= 0 && e.keyCode != 8 && e.keyCode != 46) {
tinymce.dom.Event.cancel(e);
}
});
回答by mbanchero
This is the solution that worked for me.
这是对我有用的解决方案。
I basically took the code provided by @needfulthing and fixed the errors and improved it.
我基本上采用了@needfulthing 提供的代码并修复了错误并对其进行了改进。
function initTinymce(){
tinymce.init({
selector: '.richtext-editable',
plugins: ['paste'],
max_chars: 50000, // max. allowed chars
setup: function (ed) {
var allowedKeys = [8, 13, 16, 17, 18, 20, 33, 34, 35, 36, 37, 38, 39, 40, 46];
ed.on('keydown', function (e) {
if (allowedKeys.indexOf(e.keyCode) != -1) return true;
if (tinymce_getContentLength() + 1 > this.settings.max_chars) {
e.preventDefault();
e.stopPropagation();
return false;
}
return true;
});
ed.on('keyup', function (e) {
tinymce_updateCharCounter(this, tinymce_getContentLength());
});
},
init_instance_callback: function () { // initialize counter div
$('#' + this.id).prev().append('<div class="char_count" style="text-align:right"></div>');
tinymce_updateCharCounter(this, tinymce_getContentLength());
},
paste_preprocess: function (plugin, args) {
var editor = tinymce.get(tinymce.activeEditor.id);
var len = editor.contentDocument.body.innerText.length;
if (len + args.content.length > editor.settings.max_chars) {
alert('Pasting this exceeds the maximum allowed number of ' + editor.settings.max_chars + ' characters for the input.');
args.content = '';
}
tinymce_updateCharCounter(editor, len + args.content.length);
}
});
function tinymce_updateCharCounter(el, len) {
$('#' + el.id).prev().find('.char_count').text(len + '/' + el.settings.max_chars);
}
function tinymce_getContentLength() {
return tinymce.get(tinymce.activeEditor.id).contentDocument.body.innerText.length;
}
}
回答by fralbo
Just to improve a little bit the good example given by Vladimir Miroshnichenko, to get a more accurate count, mainly for languages with accented characters.
只是为了稍微改进 Vladimir Miroshnichenko 给出的好例子,以获得更准确的计数,主要用于带有重音字符的语言。
I also inlcude the Javascript SpellChecker as the tinyMCE's one (4.1) cannot be used anymore. So the ed.addButton() will include a button in the toolbar to call $Spelling.SpellCheckInWindow('editors'). That perfectly works with tinyMCE 4.1.7.
我还包括 Javascript SpellChecker,因为 tinyMCE 的一个 (4.1) 不能再使用了。所以 ed.addButton() 将在工具栏中包含一个按钮来调用 $Spelling.SpellCheckInWindow('editors')。这与 tinyMCE 4.1.7 完美配合。
I also added a count of words, if you prefer to trig the alarm on word instead of characters.
我还添加了单词计数,如果您更喜欢在单词而不是字符上触发警报。
<textarea id="paragraph1" name="description_edit"><?=htmlspecialchars($this->company->description);?></textarea>
<div><span>Characters left:</span> <span id="chars_left"></span></div>
<script type="text/javascript" src="tinymce/tinymce.min.js"></script>
<script type="text/javascript" src="JavaScriptSpellCheck/include.js"></script>
<script>
var max_chars = 300; //max characters
var max_for_html = 1000; //max characters for html tags
var allowed_keys = [8, 13, 16, 17, 18, 20, 33, 34, 35,36, 37, 38, 39, 40, 46];
var chars_without_html = 0;
function alarmChars(){
if(chars_without_html > (max_chars - 25)){
$('#chars_left').css('color','red');
}else{
$('#chars_left').css('color','gray');
}
}
$(function() {
tinymce.init({
selector: "textarea#paragraph1",
theme: "modern",
plugins: [
"advlist autolink lists charmap preview hr anchor pagebreak",
"visualblocks visualchars insertdatetime nonbreaking",
"directionality paste textcolor"
],
menubar:false,
statusbar:false,
toolbar: "bold italic underline | alignleft aligncenter alignright alignjustify | forecolor backcolor | bullist numlist | charmap | preview | Spellcheck",
setup : function(ed) {
ed.addButton('Spellcheck', {
title : 'Spellcheck',
image : '/img/dict.png',
onclick : function() {
// Add you own code to execute something on click
$Spelling.SpellCheckInWindow('editors');
}
});
ed.on("KeyDown", function(ed,evt) {
whtml = tinyMCE.activeEditor.getContent();
without_html = whtml.replace(/(<([^>]+)>)/ig,"");
without_html = without_html.replace(/&([A-za- z])(?:acute|cedil|caron|circ|grave|orn|ring|slash|th|tilde|uml);/ig,'');
without_html = without_html.replace(/…/ig,'...');
without_html = without_html.replace(/’/ig,'\'');
without_html = $.trim(without_html.replace(/&([A-za-z]{2})(?:lig);/ig,''));
chars_without_html = without_html.length;
chars_with_html = whtml.length;
wordscount = without_html.split(/[ ]+/).length; // Just to get the wordcount, in case...
var key = ed.keyCode;
$('#chars_left').html(max_chars - chars_without_html);
if(allowed_keys.indexOf(key) != -1){
alarmChars();
return;
}
if (chars_with_html > (max_chars + max_for_html)){
ed.stopPropagation();
ed.preventDefault();
}else if (chars_without_html > max_chars-1 && key != 8 && key != 46){
alert('Characters limit!');
ed.stopPropagation();
ed.preventDefault();
}
alarmChars();
}
);
},
});
whtml = $("#paragraph1").text();
without_html = whtml.replace(/(<([^>]+)>)/ig,"");
without_html = without_html.replace(/&([A-za-z])(?:acute|cedil|caron|circ|grave|orn|ring|slash|th|tilde|uml);/ig,'');
without_html = without_html.replace(/…/ig,'...');
without_html = without_html.replace(/’/ig,'\'');
without_html = $.trim(without_html.replace(/&([A-za-z]{2})(?:lig);/ig,''));
chars_without_html = without_html.length;
$('#chars_left').html(max_chars - chars_without_html);
alarmChars();
});
I hope it will help as tinyMCE team seems to be a bit stubborn on this subject...
我希望它会有所帮助,因为 tinyMCE 团队在这个问题上似乎有点固执......
回答by Ghodrat Ashournia
the solution worked for me but with a small bug. If you see the character count is not right, thats because you use
该解决方案对我有用,但有一个小错误。如果您看到字符数不正确,那是因为您使用了
ed.on("KeyDown")
change it to
将其更改为
ed.on("KeyUp")
,then it will work fine. I havent tested it with ('Change'). it may works too!
,然后它会正常工作。我还没有用 ('Change') 测试过它。它也可以工作!
回答by Ziinloader
// Returns text statistics for the specified editor by id
function getStats(id) {
var body = tinymce.get(id).getBody(), text = tinymce.trim(body.innerText || body.textContent);
return {
chars: text.length,
words: text.split(/[\w\u2019\'-]+/).length
};
}
function submitForm() {
// Check if the user has entered less than 10 characters
if (getStats('content').chars < 10) {
alert("You need to enter 1000 characters or more.");
return;
}
// Check if the user has entered less than 1 words
if (getStats('content').words < 1) {
alert("You need to enter 1 words or more.");
return;
}
// Submit the form
document.forms[0].submit();
}
http://www.tinymce.com/wiki.php/How_to_limit_number_of_characters/words
http://www.tinymce.com/wiki.php/How_to_limit_number_of_characters/words
Hope it helps
希望能帮助到你
回答by Thariama
There is no tinymce configuration setting max_chars
, except you implement it yourself:
没有 tinymce 配置设置max_chars
,除非您自己实现:
tinyMCE.init({
...
max_chars : "10",
setup : function(ed) {
ed.onKeyDown.add(function(ed, evt) {
if ( $(ed.getBody()).text().length > ed.getParam('max_char')){
e.preventDefault();
e.stopPropagation();
return false;
}
});
}
});
回答by Paulo Almeida
Ok with the new tinyMCE4X thing's change a little bit.
好的,新的 tinyMCE4X 有一点变化。
tinymce.init({
charLimit : 10, // this is a default value which can get modified later
setup: function(editor) {
editor.on('change', function(e) {
//define local variables
var tinymax, tinylen, htmlcount;
//setting our max character limit
tinymax = this.settings.charLimit;
//grabbing the length of the curent editors content
tinylen = this.getContent().length;
if (tinylen > tinymax) {
alert('to big');
}
});
}
});