如何在CKEditor中设置部分文本不可编辑且不可删除?
解决CKEditor部分文本不可编辑且不可删除的问题
嘿,这个需求我之前帮人处理过,要让CKEditor里的指定内容只能看不能改也删不掉,同时允许用户编辑其他内容,有两种实用的方案,你可以根据自己的场景选:
方案一:针对单个元素设置只读+防删除
这种方法适合精准控制某一段内容,步骤很清晰:
- 先给需要保护的段落加个唯一ID,方便编辑器定位:
<textarea name="editor1" id="editor1" rows="10" cols="80"> <p id="protected-text">This part can not be changed</p> <p>This one can</p> </textarea>
- 在CKEditor初始化时,监听
instanceReady事件(编辑器完全加载好之后),把目标元素设为只读,同时拦截删除/退格键防止元素被移除:
CKEDITOR.replace('editor1', { on: { instanceReady: function(evt) { const editor = evt.editor; // 找到我们标记的受保护元素 const protectedEl = editor.document.getById('protected-text'); if (protectedEl) { // 把元素设为只读,用户没法编辑里面的内容 protectedEl.setReadOnly(true); // 额外拦截删除和退格键,防止用户选中整个段落删掉它 editor.on('key', function(e) { const selection = editor.getSelection(); const selectedEl = selection.getStartElement(); // 判断当前选中的是不是受保护元素或者它的子元素 const isProtected = selectedEl && (selectedEl.getId() === 'protected-text' || selectedEl.getAscendant('p', true).getId() === 'protected-text'); // 如果是,阻止删除/退格操作 if (isProtected && (e.data.keyCode === 8 || e.data.keyCode === 46)) { e.cancel(); } }); } } } });
方案二:用protectedSource批量保护内容
如果你有多个需要保护的段落,或者想用类名统一标记,这个方法更高效:
- 给需要保护的段落加个自定义类名,比如
protected-content:
<textarea name="editor1" id="editor1" rows="10" cols="80"> <p class="protected-content">This part can not be changed</p> <p>This one can</p> </textarea>
- 在CKEditor的配置里,用
protectedSource正则匹配这些段落,CKEditor会自动把它们视为不可编辑的“受保护内容”:
CKEDITOR.replace('editor1', { // 正则匹配带有protected-content类的p标签 protectedSource: /<p class="protected-content">(.*?)<\/p>/g });
这个方法的好处是不用写额外的事件监听,CKEditor会自动处理编辑和删除的限制,非常省心。
注意事项
- 以上方案适用于CKEditor 4,如果你用的是CKEditor 5,API会不一样,需要用模型层的属性来设置只读:
// CKEditor 5的示例代码 editor.model.change(writer => { const protectedEl = editor.model.document.getRoot().getChild(0); // 假设第一个元素是要保护的 writer.setAttribute('readonly', true, protectedEl); }); - 测试的时候记得多试几种操作:比如选中受保护内容按删除键、尝试修改内容、拖动选中删除,确保所有操作都被限制住。
内容的提问来源于stack exchange,提问作者Gabriel Oliveira
相关产品推荐
相关产品推荐

