CKEditor 4中a嵌套h2标签自动转换,设置allowedContent无效求助
<a> Wrapping Block Elements Hey there! I’ve dealt with this exact CKEditor 4 behavior before, so I know how annoying it is when your carefully structured HTML gets rearranged against your wishes. Let’s walk through why this happens and how to fix it.
Why This Is Happening
Even when you set config.allowedContent = true;, CKEditor 4 still enforces internal element nesting rules (via its schema system) that prioritize what it considers "standard" HTML structure. By default, the editor doesn’t expect block-level elements like <h2> to be wrapped inside inline <a> tags, so it automatically swaps their order to put the block element on the outside.
The Solution: Modify the Editor’s Schema
To let CKEditor accept <a> wrapping <h2> (and other block elements), you need to explicitly update its schema rules. Here’s how to do it in your config.js:
CKEDITOR.editorConfig = function( config ) { // Keep your existing allowedContent setting config.allowedContent = true; // Update the editor schema to allow <a> to contain block elements config.on = { instanceReady: function( editor ) { // Allow <a> to wrap <h2> specifically editor.schema.allowChildren( 'a', 'h2' ); // If you need to allow other block elements (like h1, p, div), add them here: // editor.schema.allowChildren( 'a', 'h1,h3,h4,h5,h6,p,div' ); // Optional: Ensure the filter doesn't override this editor.filter.allow( 'a h2' ); } }; // Optional: Adjust HTML Writer settings to prevent unwanted formatting changes config.htmlWriter = { sortAttributes: false, // Don't reorder attributes indentationChars: ' ', // Keep consistent indentation selfClosingEnd: '>' // Clean up self-closing tags }; };
How to Test
- Save your updated
config.js - Refresh the page with your CKEditor instance
- Switch to source mode, paste your
<a href="#"><h2>Title</h2></a>code - Switch back to WYSIWYG mode, then return to source mode—your original nesting should now be preserved!
Bonus: If You Need to Protect Specific Code
If you have one-off instances where you absolutely don’t want CKEditor touching your HTML, you can use protectedSource to mark those sections as untouchable:
config.protectedSource.push( /<a href="#">[\s\S]*?<\/a>/g );
Just note that this makes the code uneditable in the WYSIWYG mode, so it’s better to use the schema modification method if you need to edit the content normally.
内容的提问来源于stack exchange,提问作者Flaviu Jurcan

