最近剛被分配了以個訊息發布的任務,其中用到了富文字編輯器。以前也用過,不過這次我選擇的是百度富文字編輯器ueditor1_4_3-utf8-jsp版的。
其實看ueditor功能很強大,不過百度的設計還是很不錯的。只需要稍微配置一下就可以用了。
首先下載到 ueditor1_4_3-utf8-jsp.rar,串連地址是:http://ueditor.baidu.com/website/。我選擇的是utf-8版本的。
解壓以後整體拷貝到java web項目的網頁根目錄下。我這裡是用myeclipse建的項目,所以把ueditor拷貝到了WebRoot下即可。
第二步,引用ueditor/jsp/lib下的jar包。你可以選擇直接在Java Build Path中配置,或者直接放入WebRoot/WEB-INF/lib檔案夾中,項目會自動引用該檔案夾下的jar。推薦使用直接放到WEB-INF/lib下,這樣你的jar是隨著項目移動的,系統會按照相對路徑附加元件目下的jar。如果選擇第一種,如果當jar檔案移動了,那麼這個功能就會失效的。
第三步,在頁面上引入2個js檔案
<scripttype="text/javascript"src="ueditor/ueditor.config.js"></script><scripttype="text/javascript"src="ueditor/ueditor.all.js"></script>
第四步,在頁面的編輯器位置,添加html代碼
<textareaname="content" id="myEditor"></textarea> <scripttype="text/javascript"> UEDITOR_CONFIG.UEDITOR_HOME_URL = './ueditor/'; //一定要用這句話,否則你需要去ueditor.config.js修改路徑的配置資訊 UE.getEditor('myEditor'); </script>
第五步,ueditor支援圖片、文檔、音樂等檔案上傳功能,如果你想要配置上傳路徑,可以修改 ueditor/jsp/config.json。
這個檔案對於每一個配置項,都明確的文字說明。附上一段圖片上傳的配置吧:
/* 上傳圖片配置項 */ "imageActionName": "uploadimage", /* 執行上傳圖片的action名稱 */ "imageFieldName": "upfile", /* 提交的圖片表單名稱 */ "imageMaxSize": 2048000, /* 上傳大小限制,單位B */ "imageAllowFiles": [".png", ".jpg",".jpeg", ".gif", ".bmp"], /* 上傳圖片格式顯示 */ "imageCompressEnable": true, /* 是否壓縮圖片,預設是true*/ "imageCompressBorder": 1600, /* 圖片壓縮最長邊限制 */ "imageInsertAlign": "none", /* 插入的圖片浮動方式 */ "imageUrlPrefix": "", /* 圖片訪問路徑首碼 */ "imagePathFormat":"_images/image/{yyyy}{mm}{dd}/{time}{rand:6}", /* 上傳儲存路徑,可以自訂儲存路徑和檔案名稱格式 */
第六步,ueditor支援自訂功能,介面上顯示的功能都是可配置的,只要在ueditor/ueditor.config.js的toolbar中刪改配置即可,代碼如下:
//工具列上的所有的功能按鈕和下拉框,可以在new編輯器的執行個體時選擇自己需要的從新定義 , toolbars: [[ 'fullscreen', 'source', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|', 'rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|', 'directionalityltr', 'directionalityrtl', 'indent', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|', 'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|', 'simpleupload', 'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe', 'insertcode', 'pagebreak', 'template', 'background', '|', 'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|', 'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts', '|', 'searchreplace', 'help', 'drafts' ]]
看起來是6步,其實每一步都很簡單了。為了讓小夥伴們看得更清楚些,來張吧:
效果還不錯吧,其實,看起來複雜的功能,實現起來卻很簡單。而簡單的功能,實現起來可能會很複雜。我們不只是使用那麼看起來複雜,使用起來簡單的各種開源組件,更要學習,如何把複雜的功能封裝起來,對外提供簡單的介面,讓別人也能簡單使用。