wangEditor的使用
第一步,將其下載,並引入項目中。
第二步,引入js
<script type="text/javascript" src="/plugin/wangEditor/release/wangEditor.min.js"></script>
第三步,初始化對象
<span class="col-lg-8" id="editor"></span>
var E = window.wangEditor;
var editor = new E('#editor');
editor.create();
第四步,添加一些配置
配置菜單
// 自定義菜單配置
editor.customConfig.menus = [
'head', // 標題
'bold', // 粗體
'fontSize', // 字號
'fontName', // 字體
'italic', // 斜體
'underline', // 下划線
'strikeThrough', // 刪除線
'foreColor', // 文字顏色
'backColor', // 背景顏色
'link', // 插入鏈接
'list', // 列表
'justify', // 對齊方式
'quote', // 引用
'emoticon', // 表情
'image', // 插入圖片
'table', // 表格
'video', // 插入視頻
'code', // 插入代碼
'undo', // 撤銷
'redo' // 重復
];
配置圖片上傳
editor.customConfig.uploadImgServer = '/admin.php/Upload/wang_editor'; // 上傳圖片到服務器
// 3M
editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
// 限制一次最多上傳 5 張圖片
editor.customConfig.uploadImgMaxLength = 1;
// 自定義文件名
editor.customConfig.uploadFileName = 'editor_img';
// 將 timeout 時間改為 3s
editor.customConfig.uploadImgTimeout = 5000;
editor.customConfig.uploadImgHooks = {
before: function (xhr, editor, files) {
// 圖片上傳之前觸發
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,files 是選擇的圖片文件
// 如果返回的結果是 {prevent: true, msg: 'xxxx'} 則表示用戶放棄上傳
// return {
// prevent: true,
// msg: '放棄上傳'
// }
// alert("前奏");
},
success: function (xhr, editor, result) {
// 圖片上傳並返回結果,圖片插入成功之后觸發
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是服務器端返回的結果
// var url = result.data.url;
// alert(JSON.stringify(url));
// editor.txt.append(url);
// alert("成功");
},
fail: function (xhr, editor, result) {
// 圖片上傳並返回結果,但圖片插入錯誤時觸發
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是服務器端返回的結果
alert("失敗");
},
error: function (xhr, editor) {
// 圖片上傳出錯時觸發
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象
// alert("錯誤");
},
// 如果服務器端返回的不是 {errno:0, data: [...]} 這種格式,可使用該配置
// (但是,服務器端返回的必須是一個 JSON 格式字符串!!!否則會報錯)
customInsert: function (insertImg, result, editor) {
// 圖片上傳並返回結果,自定義插入圖片的事件(而不是編輯器自動插入圖片!!!)
// insertImg 是插入圖片的函數,editor 是編輯器對象,result 是服務器端返回的結果
// 舉例:假如上傳圖片成功后,服務器端返回的是 {url:'....'} 這種格式,即可這樣插入圖片:
var url = result.data[0];
insertImg(url);
// result 必須是一個 JSON 格式字符串!!!否則報錯
}
}
第五步,設置內容
// 設置內容
editor.txt.html(content);
第六步,獲取內容
// 獲取內容
var content = editor.txt.html();
很好,很方便!