CKEditor无疑是最好用的html富文本编辑器,但是js文件又比较大,用户时间和服务器空间都是宝贵的,动态加载js文件就是很好的选择,而CKEditor刚好又表现得很好,平滑过渡,用户完全无感知。
1.先定义编辑器标签
<div onfocus="loadEditor()" style="height:100px;overflow-y: auto;" id="replyEditor" name="replyEditor" contenteditable="true"></div>
一个可编辑的div,而且获得焦点我就去加载编辑器,不点击我就不加载ckeditor的文件,并且确保了点击前后样式一样
2.js代码
//动态加载js文件 function loadScript(src, callback) { var script = document.createElement('script'), head = document.getElementsByTagName('head')[0]; script.type = 'text/javascript'; script.charset = 'UTF-8'; script.src = src; if (script.addEventListener) { script.addEventListener('load', function () { callback(); }, false); } else if (script.attachEvent) { script.attachEvent('onreadystatechange', function () { var target = window.event.srcElement; if (target.readyState == 'loaded') { callback(); } }); } head.appendChild(script); } //加载编辑器 function loadEditor(){ if(typeof CKEDITOR == "undefined"){ loadScript('../plugin/ckeditor/ckeditor.js',function(){ CKEDITOR.disableAutoInline = true; CKEDITOR.inline('replyEditor',{ customConfig: '', toolbarGroups : [ { name: 'colors', groups: [ 'colors' ] }, { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker', 'editing' ] }, { name: 'forms', groups: [ 'forms' ] }, { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi', 'paragraph' ] }, { name: 'links', groups: [ 'links' ] }, { name: 'styles', groups: [ 'styles' ] }, { name: 'insert', groups: [ 'insert' ] }, { name: 'tools', groups: [ 'tools' ] }, { name: 'others', groups: [ 'others' ] }, { name: 'about', groups: [ 'about' ] } ], removeButtons : 'Source,Save,NewPage,Preview,Print,Templates,Copy,Paste,PasteText,PasteFromWord,Cut,Undo,Redo,Find,Replace,SelectAll,Scayt,Form,Checkbox,Radio,TextField,Textarea,Select,Button,ImageButton,HiddenField,CopyFormatting,RemoveFormat,Outdent,Indent,CreateDiv,Blockquote,JustifyLeft,JustifyCenter,JustifyRight,JustifyBlock,BidiLtr,BidiRtl,Language,Link,Unlink,Anchor,Image,HorizontalRule,Table,Smiley,SpecialChar,Iframe,PageBreak,About,Maximize,Styles,Format,Font,FontSize,ShowBlocks,Flash' }); }); } }
3.效果
效果图我就不贴了,反正这种动态异步加载和页面全部一起加载的效果完全无差别,用户无感知。