限制所见即所得编辑器(NicEdit)中的字符数
我有这个jQuery代码:
I have this jQuery code:
var char = 60;
$("#counter").append("You have <strong>" + char + "</strong> char.");
$("#StatusEntry").keyup(function () {
if ($(this).val().length > char) {
$(this).val($(this).val().substr(0, char));
}
var rest = char - $(this).val().length;
$("#counter").html("You have <strong>" + rest + "</strong> char.");
if (rest <= 10) {
$("#counter").css("color", "#ff7777");
}
else {
$("#counter").css("color", "#111111");
}
});
效果很好! 但是,如果改为使用val()却有text()则不起作用.
It works fine! But if instead a val() I have text() it doesn't work.
问题是,在可用字符的末尾,它开始从头开始替换文本……使用val是完美的.
The problem is that at the end of available char it start to replace the text from the beginning...... using val is perfect.
为什么我在文字上需要它? 因为我使用的是wysiwyg插件,它将我的textarea转换为div.
Why I need it on text? Because I'm using a wysiwyg plugin and it convert my textarea to div.
我正在尝试使用.stopPropagation,但是它不起作用..尝试使用return false和什么都没有...
I'm trying with .stopPropagation but it doesn't work.. trying with return false and nothing...
希望在您的帮助下!
如果您需要使用NicEdit,则可以通过将keyup/keydown事件绑定到新创建的div来限制击键(它不会替换您的textarea-它的文本区域添加一个div并隐藏您的textarea):
If you need to use the NicEdit then you can limit the keystrokes by binding the keyup / keydown event to the newly created div (it doesnt replace your textarea - its adds a div and hides your textarea) :
$("#StatusEntry").prev().keydown(function () {
之所以可行,是因为新创建的div始终位于文本区域的前面-因此这将适用于多个编辑器.
This works because the newly create div is always preceding the textarea - so this will work for multiple editors.
但是,正如您似乎在注释中指出的那样,如果使用以下方法,则contentEditable div可能就足够了:
However as you seem to have indicated in your comments a contentEditable div may be sufficient - if it is use the following method :
var char = 60;
$("#counter").append("You have <strong>" + char + "</strong> char.");
$("#StatusEntry").keyup(function () {
if ($(this).text().length > char) {
$(this).text($(this).text().substr(1));
}
var rest = char - $(this).text().length;
$("#counter").html("You have <strong>" + rest + "</strong> char.");
if (rest <= 10) {
$("#counter").css("color", "#ff7777");
}
else {
$("#counter").css("color", "#111111");
}
});