近期在產品的開發工作中遇到要使用富文本編輯器的地方。於是對比了幾款編輯器, 最后選擇了wangEditor。
優點:輕量、簡潔、界面美觀、文檔齊全。 缺點: 相較於百度ueditor等編輯器功能較少。 文檔地址:https://www.kancloud.cn/wangfupeng/wangeditor3/332599
使用方式:
1. 創建一個容器 :
<div id="editor"> </div>
2.引入js文件
<script src="~/Editor/wangEditor.js"></script>
3.初始化
// 富文本編輯器 var E = window.wangEditor; var editor = new E("#editor")
editor.create()
4.上傳圖片
支持網絡圖片與本地上傳
網絡圖片直接輸入地址即可。
本地上傳默認是關閉的。分為Base64與上傳至服務器。
4.1 Base64格式
開啟本地上傳Base64
// 啟用"上傳圖片"tab base64格式 editor.customConfig.uploadImgShowBase64 = true;
開啟之后直接拖拽或手動選擇上傳即可。
Base64碼
4.2 上傳至服務器
配置上傳接口,但是不能與Base64同時配置。
editor.customConfig.uploadImgServer = '/Storage/Upload'
js上傳配置:用的官方文檔的默認配置。 詳情可以參考官網文檔:https://www.kancloud.cn/wangfupeng/wangeditor3/335782
注:所有的配置代碼都需要放在 editor.create() 之前。
editor.customConfig.uploadImgHooks = { before: function (xhr, editor, files) { // 圖片上傳之前觸發 // xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,files 是選擇的圖片文件 // 如果返回的結果是 {prevent: true, msg: 'xxxx'} 則表示用戶放棄上傳 // return { // prevent: true, // msg: '放棄上傳' // } }, success: function (xhr, editor, result) { // 圖片上傳並返回結果,圖片插入成功之后觸發 // xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是服務器端返回的結果 }, fail: function (xhr, editor, result) { console.log(result) // 圖片上傳並返回結果,但圖片插入錯誤時觸發 // xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是服務器端返回的結果 }, error: function (xhr, editor) { // 圖片上傳出錯時觸發 // xhr 是 XMLHttpRequst 對象,editor 是編輯器對象 }, timeout: function (xhr, editor) { // 圖片上傳超時時觸發 // xhr 是 XMLHttpRequst 對象,editor 是編輯器對象 }, // 如果服務器端返回的不是 {errno:0, data: [...]} 這種格式,可使用該配置 // (但是,服務器端返回的必須是一個 JSON 格式字符串!!!否則會報錯) customInsert: function (insertImg, result, editor) { // 圖片上傳並返回結果,自定義插入圖片的事件(而不是編輯器自動插入圖片!!!) // insertImg 是插入圖片的函數,editor 是編輯器對象,result 是服務器端返回的結果 // 舉例:假如上傳圖片成功后,服務器端返回的是 {url:'....'} 這種格式,即可這樣插入圖片: var url = result.Url insertImg(url) // result 必須是一個 JSON 格式字符串!!!否則報錯 } }
4.3 后端接口
只需將文件的最終存儲路徑按指定的格式/或自定義格式放回即可。
5.將編輯器內的數據傳遞給后台方法
我這里是先將編輯器內的數據賦值給 textarea ,然后使用ajax的方式提交textarea的數據。
5.1 創建textarea 並隱藏
<textarea id="text1" style="width:100%; height:200px;display:none;"></texta
5.2 在js中配置
// 隱藏的文本域 var $text1 = $('#text1') // 監聽編輯器內容的變化,html為變化后的數據 editor.customConfig.onchange = function (html) { // 監控變化,同步更新到 textarea $text1.val(html) }
5.3 提交數據並在后台保存
添加一個按鈕
<button id="btnSubmit2">保存 </button>
ajax提交
$("#btnSubmit2").click(function () { // 文本域的內容 var text1 = $('#text1').val(); $.ajax({ type: "post", data: { "editorHtml": text1 }, url: "/Editor/Save", success: function (data) { console.log(data) }); })
6.其他配置及功能請直接訪問文檔:
https://www.kancloud.cn/wangfupeng/wangeditor3/335782