You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CKEditor中使用onKeyUp函数实现剩余字符统计

实现CKEditor实时剩余字符统计

我来帮你搞定这个CKEditor实时统计剩余字符数的问题!首先得注意,CKEditor是基于iframe的富文本编辑器,不能直接给DOM元素绑定onKeyUp事件,得用它自带的事件监听机制才行。下面是完整的实现方案:

1. 补全HTML结构

先把你给出的HTML补全为完整结构:

<div class="row">
  <div class="col-xs-12 col-sm-6 inputBlock textareaRegion">
    <div id="editor1" class="textarea"></div>
    <label class="showLabel">Comments</label>
    <div class="maxlengthCountDiv">
      Remaining character length: <span class="maxlengthCount"></span>
    </div>
  </div>
</div>

2. 初始化CKEditor并绑定事件

这是核心的JavaScript代码,我们会初始化编辑器,监听内容变更事件,实时计算剩余字符数:

// 设定允许的最大字符数,可根据需求修改
const MAX_CHARACTERS = 500;

// 初始化CKEditor
ClassicEditor
  .create(document.querySelector('#editor1'))
  .then(editor => {
    // 获取显示剩余字符的DOM元素
    const remainingCountEl = document.querySelector('.maxlengthCount');
    // 初始化显示剩余字符数
    remainingCountEl.textContent = MAX_CHARACTERS;

    // 监听编辑器内容变更事件(覆盖键盘输入、粘贴、工具栏操作等所有场景)
    editor.model.document.on('change:data', () => {
      // 获取编辑器纯文本内容(过滤HTML标签,统计用户实际输入的文本)
      const plainText = editor.getData().replace(/<[^>]+>/g, '');
      // 计算已使用字符数
      const usedCharacters = plainText.length;
      // 计算剩余字符数,确保不会出现负数
      const remainingCharacters = Math.max(MAX_CHARACTERS - usedCharacters, 0);
      // 更新页面显示
      remainingCountEl.textContent = remainingCharacters;

      // 可选:剩余字符不足时添加红色提示
      if (remainingCharacters < 50) {
        remainingCountEl.style.color = '#dc3545';
      } else {
        remainingCountEl.style.color = '';
      }
    });
  })
  .catch(error => {
    console.error('CKEditor初始化失败:', error);
  });

关键细节说明

  • 为什么用change:data而不是keyup?因为CKEditor的内容变更不止来自键盘输入,粘贴内容、点击工具栏插入元素等操作都会触发这个事件,能确保统计的准确性。
  • 如果需要统计包含HTML标签的总字符数,直接替换为const usedCharacters = editor.getData().length即可。
  • Math.max(...)的作用是避免剩余字符数出现负数,提升用户体验。

内容的提问来源于stack exchange,提问作者shine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:47:20