For a new project of mine I’m using a rich text editor called CKEditor. This is a highly configurable editor that, unfortunately, suffers from cluttered and not easily understandable documentation. I needed to change the generated HTML from the editor so that images that were resized not only had their size set as style attributes, but as query string variables. So I needed this:
<img src="http://yoursite.com/photo.jpg" style="width:150px; height:200px;" /> to be output as this:
<img src="http://yoursite.com/photo.jpg?width=150&height=200" style="width:150px; height:200px;" /> That proved to be easier said than done, but after quite a lot of googling, asking on several forums, and getting some helpful (and some not helpful at all) replies, I finally ended up with the following: Put the following code into CKEditor’s config.js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
CKEDITOR.on('instanceReady', function (ev) { var editor = ev.editor, dataProcessor = editor.dataProcessor, htmlFilter = dataProcessor && dataProcessor.htmlFilter; htmlFilter.addRules( { elements : { $ : function( element ) { // Output dimensions of images as width and height attributes on src if ( element.name == 'img' ) { var style = element.attributes.style; if (style) { // Get the width from the style. var match = /(?:^|\s)width\s*:\s*(\d+)px/i.exec( style ), width = match && match[1]; // Get the height from the style. match = /(?:^|\s)height\s*:\s*(\d+)px/i.exec( style ); var height = match && match[1]; var imgsrc = element.attributes.src + "?width=" + width + "&height=" + height; element.attributes.src = imgsrc; element.attributes['data-cke-saved-src'] = imgsrc; } } } } }); }); |
This code is run whenever the CKEditor generates the […] Read more