计算aloha编辑器中文本区域的字符数

count characters of textarea in aloha editor

本文关键字:字符 区域 文本 aloha 编辑器 中文 计算      更新时间:2023-09-26

我的html代码如下:

<div class="control-group">
  <label class="control-label">Message Body
    <p class="showlimit"><!-- this shows character limit for the message -->
         <span id="charsLeft"></span>/<span id="charsLimit"></span>
    </p>
  </label>
  <div class="controls">
    <textarea rows="7" id="msg" name="msg" class="field span5"></textarea>
  </div>
</div>

我的jquery代码是这样的:

$('#charsLimit').text(1200);
$('#msg').limit($('#charsLimit').text(),'#charsLeft');

我想显示id中剩余的字符数charsLeft(共1200个)(即charsLimit的值)在正常情况下,它可以工作,但在使用Aloha编辑器的富编辑级别上,它不起作用,因为它用div替换了文本区域,如下所示:

<!-- rest of the above code is same -->
<div class="controls">
  <textarea id="msg" class="field span5" name="msg" rows="7" 
      style="display: none;"><!-- observe the style displaying none -->
  </textarea>
  <!-- 
     msg replaced with msg-aloha hence not able to perform normal jquery on msg 
  -->
  <div id="msg-aloha" class="aloha-textarea aloha-editable 
        aloha-block-blocklevel-sortable ui-sortable" 
        contenteditable="true" style="height: 140px; width: 456px;">
      <br class="aloha-cleanme" style="">
  </div>
</div>

我不知道该怎么办…

查看ContentEditablediv 中的限制字符数

尝试

$('#charsLimit').text(1200);
$('#msg-aloha').keyup(function(e){ $('#charsLeft').text($('#charsLimit').text() -check_charcount(e)); });
function check_charcount(e)
{   
    var char_count = $('#msg-aloha').text().length;
    if(e.which != 8 && char_count >= $('#charsLimit').text())
    {
        e.preventDefault();
    }
    return char_count;
}