
本教程旨在解决ckeditor 4.5.x及更高版本在粘贴外部内容时自动移除`
CKEditor作为一款功能强大的富文本编辑器,在处理用户输入和粘贴内容时,为了保证编辑内容的规范性、安全性和一致性,内置了多层过滤机制。然而,在某些特定场景下,这些过滤机制可能会超出预期,导致用户从外部网站复制粘贴的HTML内容(特别是
CKEditor的过滤机制主要分为两大类:
问题通常出现在CKEditor 4.5.X及更高版本中,即使配置了config.allowedContent = true;或config.extraAllowedContent = 'div span';,
许多开发者在遇到此问题时,首先会尝试调整config.allowedContent或config.extraAllowedContent。例如:
立即学习“前端免费学习笔记(深入)”;
// config.js 或 CKEDITOR.editorConfig 函数内
CKEDITOR.editorConfig = function(config) {
config.allowedContent = true; // 允许所有内容
config.format_tags = 'p;h1;h2;h3;pre;div'; // 允许div作为格式标签
config.extraAllowedContent = 'div span(*)[*]{*}'; // 额外允许div和span及其所有属性和样式
};然而,对于粘贴时移除
解决此问题的关键在于调整config.pasteFilter设置。当config.pasteFilter被设置为null时,CKEditor将禁用其默认的粘贴内容清理过滤器,从而允许粘贴的原始HTML内容(包括
配置方法:
在您的CKEditor配置文件(通常是config.js)中,或者在初始化CKEditor实例时,添加以下配置:
// config.js 或 CKEDITOR.editorConfig 函数内
CKEDITOR.editorConfig = function(config) {
// 其他CKEditor配置...
// 禁用默认的粘贴过滤器,确保粘贴时保留所有HTML标签
config.pasteFilter = null;
// 您可以保留其他内容过滤配置,以在pasteFilter禁用后继续规范编辑区内容
// config.allowedContent = true;
// config.extraAllowedContent = 'div span(*)[*]{*}';
};示例代码:
假设您的config.js文件如下:
CKEDITOR.editorConfig = function(config) {
// The toolbar groups arrangement, optimized for two toolbar rows.
config.toolbarGroups = [
{ name: 'clipboard', groups: [ 'clipboard', 'undo' ] },
{ name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] },
{ name: 'links' },
{ name: 'insert' },
{ name: 'forms' },
{ name: 'tools' },
{ name: 'document', groups: [ 'mode', 'document', 'doctools' ] },
{ name: 'others' },
'/',
{ name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
{ name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] },
{ name: 'styles' },
{ name: 'colors' },
{ name: 'about' }
];
// Remove some buttons provided by the standard plugin.
config.removeButtons = 'Underline,Strike,Subscript,Superscript,Anchor,Styles,Specialchar';
// Set the most common block elements.
config.format_tags = 'p;h1;h2;h3;pre;div';
// Simplify the dialog windows.
config.removeDialogTabs = 'image:advanced;link:advanced';
// 禁用默认的粘贴过滤器,确保粘贴时保留所有HTML标签
config.pasteFilter = null;
// 允许所有内容(如果需要,可以保留)
config.allowedContent = true;
// 额外允许div和span(如果需要,可以保留)
config.extraAllowedContent = 'div span(*)[*]{*}';
};完成上述配置后,当用户从外部网站复制包含
尽管config.pasteFilter = null;能有效解决特定问题,但在实际应用中,您需要权衡其带来的潜在影响:
当CKEditor 4.5.X及更高版本在粘贴外部内容时,意外移除
以上就是CKEditor粘贴内容时保留HTML标签的配置指南的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号