一、功能介紹
layedit是一款基於layui框架的富文本編輯器,適用於後台管理系統、博客編輯等場景,提供了很多實用的功能,包括但不限於:
- 字體、字型大小、顏色設置
- 加粗、斜體、下劃線、刪除線等文字樣式設置
- 圖片、鏈接、表格、列表插入
- 源代碼、全屏、撤銷、重做等操作
- 自定義工具欄
二、使用方法
使用layedit非常簡單,只需要引入layui和layedit的腳本文件,然後在需要使用編輯器的地方添加一個textarea元素即可:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>layedit富文本編輯器</title> <link rel="stylesheet" href="layui/css/layui.css"> <script src="layui/layui.js"></script> </head> <body> <textarea id="content" name="content"></textarea> <script> layui.use('layedit', function(){ var layedit = layui.layedit; layedit.build('content'); }); </script> </body> </html>
三、工具欄定製
layedit默認提供的工具欄可以滿足常規需求,但如果需要添加、刪除、修改工具欄的按鈕,就需要使用定製功能。
首先,在layedit.build()中傳入一個配置對象,配置項包括:
- tool: 工具欄數組
- height: 編輯區域高度
- uploadImage: 圖片上傳介面
- hideTool: 隱藏工具欄
- devmode: 開發者模式(查看html源碼)
然後在tool中定義需要的按鈕,示例代碼如下:
layui.use('layedit', function(){ var layedit = layui.layedit; //自定義工具欄 layedit.build('content', { tool: [ 'strong', 'italic', 'underline', 'del', '|', 'color', 'link', 'image', 'blockquote', '|', 'table', 'face', 'code', '|', 'left', 'center', 'right' ] }); });
上述代碼定義了一個包含18個按鈕的工具欄,可根據自己的需要修改。
四、圖片上傳
layedit提供了圖片上傳功能,只需要在layedit.build()中定義uploadImage參數,介面返回值格式如下:
{ "code": 0, "msg": "", "data": { "src": "http://cdn.xxx.com/abc.jpg" } }
其中code為0表示上傳成功,data.src為圖片的線上地址。
示例代碼:
layedit.build('content', { uploadImage: { url: '/upload/image', type: 'post' } });
五、事件監聽
layedit提供了多個事件供開發者監聽。
- tool(elem, edit): 工具欄被點擊時觸發
- ready(index): 載入完畢時觸發
- change(index): 內容改變時觸發
- face(index): 表情被點擊時觸發
- insert(html): 插入內容後觸發
示例代碼:
layui.use('layedit', function(){ var layedit = layui.layedit; layedit.build('content', { tool: [ 'strong', 'italic', 'underline', 'del', '|', 'color', 'link', 'image', 'blockquote', '|', 'table', 'face', 'code', '|', 'left', 'center', 'right' ], uploadImage: { url: '/upload/image', type: 'post' }, //監聽事件 tool: function(elem, edit){ console.log(elem); //工具欄元素 console.log(edit); //編輯器實例 }, ready: function(index){ console.log(index); //編輯器索引 }, change: function(index){ console.log(index); }, face: function(index){ console.log(index); }, insert: function(html){ console.log(html); } }); });
原創文章,作者:OUXRZ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/369320.html