nmgxzm00 2013-07-23
转http://www.cnblogs.com/Fskjb/archive/2009/11/16/1603461.html
安装: 下载CKEDITOR的文件,解压后复制到工程的WEBROOT目录下就OK!
引用CKEDITOR的JS文件:
新建JSP页面,添加其JS文件<scripttype="text/javascript"src="ckeditor/ckeditor.js"></script>
注意:1.src的路径。
2.不要写成<scripttype="text/javascript"src="ckeditor/ckeditor.js/>样式,在现有的3.0.1版本中会出现CKEDITOR未定义的脚本错误提示,致使不能生成编辑器。
替换TEXTAREA标签:
<textarea rows="30" cols="50" name="editor01">请输入.</textarea> <script type="text/javascript">CKEDITOR.replace('editor01');</script>
注意:要在textarea后面加入javascript.如果要在HEAD区写javasript,那么采用如下代码:
<script type="text/javascript"> window.onload = function() { CKEDITOR.replace( 'editor01' ); }; </script>
好了到此一个默认的CKEDITOR就配置完毕了,可以去页面看看它的模样了。
当然还有一个方法CKEDITOR.appendTo(elementOrId,config)它可以在特定的dom对象中创建CKEDITOR
<div id="editorSpace"><:/div> CKEDITOR.appendTo( 'editorSpace' );
属性配置:
所有的配置,都可以查阅官方的API:
版本3
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html
版本4
http://docs.ckeditor.com/#!/api/CKEDITOR.config
IN-PAGE配置方式:
Thebestwaytosetyourconfigurationsisin-page,whencreatingeditorinstances.InthiswayyouavoidtouchingtheoriginaldistributionfilesintheCKEditorinstallationfolder,makingtheupgradetaskeasier.
最好在创建编辑器的页面中配置你的编辑器属性,使用这种方式,你无需理会在CKEDITOR安装目录中的配置文件(ps:in-page的优先级最高)
CKEDITOR.replace( 'editor1', { toolbar : 'Basic', uiColor : '#9AB8F3' });
注意:合法的属性是以“{”开始,“}”"结束,属性名和属性值用“:”隔离.
默认属性文件配置方式:
Youcanalsoplaceyoursettingsinsidetheconfig.jsfilealso.Youwillnotethatthefileismostlyemptybydefault.Yousimplyneedtoaddtheconfigurationsthatyouwanttochange.Forexample:
你也可以在config.js中加入配置信息,当你打开该文件时你会发觉它几乎为空(默认)。你要做的是把配置信息加入其中。
CKEDITOR.editorConfig = function( config ) { config.language = 'fr'; config.uiColor = '#AADC6E'; };
自定义属性文件配置方式:
Supposeyouhavecopiedconfig,jsinsideafoldernamed"custom"intherootofyourwebsite.Youhavealsorenamedthefileto"ckeditor_config.js".Atthatpoint,youmustonlysetthecustomConfigsettingwhencreatingtheeditorinstances.Forexample:
CKEDITOR.replace( 'editor1', { customConfig : '/custom/ckeditor_config.js' });
假设你在custom目录中有一自定义的配置文件ckeditor_config.js,那么就必须在创建ckeditor实例时制定它的路径(用customConfig属性)。
ConfigurationsOverloadOrder配置的优先级
You'renotrequiredtouseonlyoneoftheaboveconfigurationoptions.Youcanmixallofthem,andtheconfigurationswillbeoverloadedproperly.Thefollowingisconfigurationsloadingorderwhencreatinganeditorinstance:
你不必仅使用上面的一种方式进行配置,而是可以混合使用它们,这些配置会以特定的优先级顺序进行复写。
1.Theeditorinstanceiscreated.Atthispointallitsdefaultconfigurationsareset.
编辑器创建的那一瞬间,会加载默认的配置信息。
2.IfthecustomConfigsettinghasbeenset"in-page",thatfileisloaded,otherwisethedefaultconfig.jsfileisloaded.Allsettingsinthisfileoverridethecurrentinstancesettings.
这时,如果系统发现我们制定了一个自定义的配置文件,那么就会加载它,否则就会加载默认的配置文件。加载的该文件的属性将会复写当前实例的属性。
3.Ifthesettingsloadedinpoint"2"alsodefineanewcustomConfigvalue,thisnewfileisloadedanditssettingsoverloadthecurrentinstancesettings.ThishappensrecursivelyforallfilesuntilnocustomConfigisdefined.
如果在自定义的文件中有加入新的其它自定义文件,那么新的文件会复写当前实例的属性。这样一直循环递归,知道没有新为自定义文件为止。
4.Finallythesettingsdefined"in-page"overridethecurrentinstancesettings(exceptcustomConfig,whichhasbeenusedatpoint"1").
最后行内的属性(除了customConfig)将复习当前实例的属性。
AvoidingLoadingExternalSettingsFiles
Itisalsopossibletocompletelyavoidloadinganexternalconfigurationfile,reducingthenumberoffilesloaded.Todothat,it'senoughtosetthecustomConfigsettingtoanemptystring.Forexample:
CKEDITOR.replace( 'editor1', {customConfig : ''});
Thissettingisdefinitelyrecommende
difyouarenotsettingconfigurationsintheconfig.jsfilenoracustomconfigurationfile.
这段就不翻译了,so,easy!
配置个性化工具栏:
AtoolbardefinitionisaJavaScriptarraythatcontainstheelementstobedisplayedinall"toolbarrows"availableintheeditor.Therearetwowaystosetthedesiredtoolbardefinitionintheeditor.Itcanbesetdirectlyintothe"toolbar"setting,oritcaninsteadbesettoaconfigurationnamed"toolbar_<name>",where"<name>"isanamethatcanbeusedtoidentifythetoolbarinthe"toolbar"setting.Thefollowingisthedefaultsettingwehaveintheeditor.
上面的英文太罗嗦了说重点算了:工具栏是通过数组来设定的,工具栏的名字以toolbar_<name>的方式命名,其中的<name>是用来赋值给config.toolbar这一变量的。
那么以下代码定义了toolbar_Full和toolbar_Basic的两种工具栏配置,并使用了config.toolbar='Full';定义当前的编辑器的工具栏为Full。
其中("-")为空间栏的水平分割,("/")为换行。
config.toolbar = 'Full'; config.toolbar_Full = [ ['Source','-','Save','NewPage','Preview','-','Templates'], ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'], ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'], ['Form', 'Checkbox', 'Radio', 'TextField', 'Textarea', 'Select', 'Button', 'ImageButton', 'HiddenField'], '/', ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'], ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'], ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'], ['Link','Unlink','Anchor'], ['Image','Flash','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'], '/', ['Styles','Format','Font','FontSize'], ['TextColor','BGColor'], ['Maximize', 'ShowBlocks','-','About'] ]; config.toolbar_Basic = [ ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink','-','About'] ];
Notethattwotoolbardefinitionshavebeendefined,onenamed"Full"andtheother"Basic".The"Full"definitionhasbeensettobeusedinthetoolbarsetting.
Youcancreateasmanytoolbardefinitionsasyouwantinsidetheconfigurationfile.Later,basedonsomecriteria,youcandecidethetoolbartouseforeacheditorinstance.Forexample,withthefollowingcode,twoeditorsarecreatedinthepage,eachoneusingadifferenttoolbar:
你也可以根据您的需要在配置文件中建立多个工具栏的定义,然后,可以根据特定条件,决定使用哪个定义。
CKEDITOR.replace( 'editor1', {toolbar : 'MyToolbar'}); CKEDITOR.replace( 'editor2', {toolbar : 'Basic'});
It'salsopossibletosetthetoolbardefinitionin-page,whencreatingtheeditorinstancedirectly.Inthatcase,justassignittothetoolbarsettingdirectly,forexample:
也可以通过IN-PAGE的方式定义工具栏参数。
CodeCKEDITOR.replace( 'editor1',{ toolbar :[ ['Styles', 'Format'], ['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', '-', 'About'] ] });
TheStylesDefinition
ThestylesdefinitionisaJavaScriptarraywhichisregisteredbycallingtheCKEDITOR.addStylesSet()function.Auniquenamemustbeassignedtoyourstyledefinition,soyoucanlaterseteacheditorinstancetoloadit.Itmeansthatyoucanhaveasinglestyledefinitionwhichissharedbyseveraleditorinstancespresentonthepage.
Thefollowingisasamplestyledefinitionregistration:
通过CKEDITOR.addStylesSet()函数,我们可以定义一个样式,结合以下的例子,my_styles为样式的名称,具体的样式为一个JAVASCRIPT数组。通过样式的名称我可以让页面的多个编辑器应用该样式。
CKEDITOR.addStylesSet( 'my_styles', [// Block Styles {name:'Blue Title',element:'h2',styles:{'color' : 'Blue'}}, {name:'Red Title',element:'h3',styles:{ 'color' : 'Red' }}, // Inline Styles {name:'CSS Style',element:'span',attributes:{'class':'my_style'}}, {name:'Marker:Yellow',element:'span',styles:{'background-color':'Yellow'}} ] );
Theabovedefinitionregistrationcanbeplacedinlineinthepageusingtheeditor,orcanevenliveinanexternalfile,whichisloaded"ondemand",whenneededonly(seebelow).
样式可以通过IN-PAGE或配置文件中进行注册。
Afterthat,youmustinstructtheeditortouseyournewlyregisteredstyledefinitionbyusingthestylesCombo_stylesSetsetting.Thismaybesetintotheconfig.jsfile,forexample:
你可以通过在config.js加入以下代码使编辑器应用该样式:
config.stylesCombo_stylesSet = 'my_styles';
UsinganExternalStylesDefinitionFile使用自定义的样式文件
YoucanincludetheabovestylesdefinitionregistrationcallintoanexternalJavaScriptfile.ThisisthepreferredwayforitbecauseitwillbeloadedonlywhenopeningtheStylesselectionbox,enhancingthepageloadingperformance.Usersmayfeelasmallloadinggapbecauseofitthough.
Bydefault,theeditorusesthe"plugins/stylescombo/styles/default.js"file,whichisa"minified"JavaScriptfile.Youcanfindtheuncompressedversionofitat"_source/plugins/stylescombo/styles/default.js".YoucanseeitonlineatourSVNalso:http://svn.fckeditor.net/CKEditor/trunk/_source/plugins/stylescombo/styles/default.js.Itcanbeusedasatemplateforyourcustomfile.
Yourstyledefinitionfilecanbesavedanywhereatyourwebsite(ortheweb).YoumustjustknowtheURLtoreachit.Forexample,youcansaveatitattherootofyourwebsite,soyoucanreachitwith"/styles.js",orevenplaceitinacentralwebsite,soyoucanlocateitwith"http://www.example.com/styles.js".Atthatpoint,simplychangethestylesCombo_stylesSetsettingtopointtheeditortoyourfile:
默认的样式文件在"_source/plugins/stylescombo/styles/default.js"目录中,我们也可以自己定义一个样式文件,如在站点的跟目录中有styles.js这一个样式文件,这个文件通过以下代码指定其路径:
config.stylesCombo_stylesSet = 'my_styles:/styles.js';ORconfig.stylesCombo_stylesSet = 'my_styles:http://www.example.com/styles.js';Style Rules
Theentriesinsideastyledefinitionarecalled"stylerules".Eachruledefinesthedisplaynameforasinglestyleaswellastheelement,attributesandcssstylestobeusedforit.Thefollowingisthegenericrepresentationforit:
{ name:'Display name', element:'tag name(for example "span")', styles:{'css-style1':'desired value','css-style2':'desired value',} attributes:{'attribute-name1':'desired value','attribute-name2':'desired value',} }
The"name"and"element"valuesarerequired,whileothervaluesareoptional.
StyleTypes
Therearethreetypesofstyletypes,eachonerelatedtotheelementusedinthestylerule:
•Blockstyles:appliedtothetextblocks(paragraphs)asawhole,notlimitedtothetextselection.Theelementsvaluesforthatare:address,div,h1,h2,h3,h4,h5,h6,pandpre.
•Objectstyles:appliedtospecialselectableobjects(nottextual),wheneversuchselectionissupportedbythebrowser.Theelementsvaluesforthatare:a,embed,hr,img,li,object,ol,table,td,trandul.
•Inlinestyles:appliedtotextselectionsforstylerulesusingelementsnotdefinedintheotherstyletypes.
OutputFormatting
TheHTMLWriter
这个是用来对各种标签的排版进行设定的
Technicallyspeaking,writingthefinaloutputisataskexecutedbytheCKEDITOR.htmlWriterclass("writer"),usedbytheCKEDITOR.htmlDataProcessorclass.Therefore,thecurrentwriterinstanceforaspecificeditorinstancecanberetrievedbythe<editorInstance>.dataProcessor.writerproperty.
Bysettingthewriterproperties,it'spossibletoconfigureseveraloutputformattingoptions.Thefollowingexampleisthebestwaytosummarizethemostusedofthem,withtheirdefaultvalues:
var writer = editor.dataProcessor.write; // The character sequence to use for every indentation step. writer.indentationChars = '\t'; // The way to close self closing tags, like <br />. writer.selfClosingEnd = ' />'; // The character sequence to be used for line breaks. writer.lineBreakChars = '\n'; // Set writing rules for the <p> tag. writer.setRules( 'p', { // Indicates that this tag causes indentation on line breaks inside of it. indent : true, // Insert a line break before the <p> tag. breakBeforeOpen : true, // Insert a line break after the <p> tag. breakAfterOpen : true, // Insert a line break before the </p> closing tag. breakBeforeClose : false, // Insert a line break after the </p> closing tag. breakAfterClose : true })
SettingWriterRules
Becausethewriterisapropertyofeacheditorinstance,andalsobecauseit'sdependencyonthewriterplugintobeloaded,thebestwaytomakechangestoitisbylisteningtothe"instanceReady"event,soit'ssafetoassumethatthedataProcessorpropertywillbeloadedandreadytochanges.Thefollowingisanexampleofit,whencreatinganeditorinstance:
可以为单一得编辑器指定标签的格式。
CKEDITOR.replace( 'editor1', {on :{ instanceReady : function( ev ){ // Output paragraphs as <p>Text</p>. this.dataProcessor.writer.setRules( 'p',{ indent :false, breakBeforeOpen : true, breakAfterOpen : false, breakBeforeClose : false, breakAfterClose :true }); } } });
AnotherwayforitisbyusingtheCKEDITORobject,soalleditorinstanceswillbechanged:
也可以对所有的编辑器进行设定。
CKEDITOR.on( 'instanceReady', function( ev ){ // Out self closing tags the HTML4 way, like <br>. ev.editor.dataProcessor.writer.selfClosingEnd = '>'; });
$oFCKeditor->Value = 'This is some <strong>sample text</strong>' ;<textarea name="content" style=&qu