超好用的富文本编辑器froalaEditor(方便传图片和视频等)
? ? ? ?最近項目有個文章管理功能,我對比了很多富文本編輯器,有的是上傳圖片不方便,有的是復(fù)制粘貼不方便,有的是但編輯器里面不能改變圖片大小,最后,我找到了froalaEditor,可以說是集各種功能為一身,不但界面清爽,功能也十分全面,插入圖片和視頻都很方便,自己可以到官網(wǎng)體驗一下:https://www.froala.com/wysiwyg-editor
官方文檔地址:https://www.froala.com/wysiwyg-editor/docs
由于官方提供的下載包沒有第三方插件,不太全,所以自己整理了全面的插件
插件下載地址:
https://download.csdn.net/download/lianzhang861/10756460
代碼:
<!DOCTYPE HTML> <html> <head><!-- Include external CSS. --><link href="${ctx }/common/static/froala_editor_2.8.5/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" /><link rel="stylesheet" href="${ctx }/common/static/froala_editor_2.8.5/codemirror/codemirror-5.40.2/lib/codemirror.css"><link href="${ctx }/common/static/froala_editor_2.8.5/css/themes/dark.min.css" rel="stylesheet" type="text/css" /><!-- Include Editor style. --><link href="${ctx }/common/static/froala_editor_2.8.5/css/froala_editor.pkgd.min.css" rel="stylesheet" type="text/css" /><link href="${ctx }/common/static/froala_editor_2.8.5/css/froala_style.min.css" rel="stylesheet" type="text/css" /><title>創(chuàng)建文章</title> </head> <body> <article class="page-container" style="margin-left:25px;"><input type="hidden" name="articleId" id="articleId" value="${article.article_id}"/><div class="row cl" ><div id="artcleName"><input type="text" class="input-text" placeholder="輸入文章標(biāo)題" style="background:#eee;margin-bottom:10px;"></div><div id="edit"></div></div><div class="row cl" style="margin:50px 0;"><div class="col-xs-8 col-sm-7 col-xs-offset-4 col-sm-offset-3"><input class="btn btn-primary radius" type="button" onclick="saveArticle()" value=" 提交 "></div></div> </article> <script type="text/javascript" src="${ctx}/common/lib/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript" src="${ctx}/common/lib/layer/2.4/layer.js"></script> <script type="text/javascript" src="${ctx }/common/static/froala_editor_2.8.5/codemirror/codemirror-5.40.2/lib/codemirror.js"></script> <script type="text/javascript" src="${ctx }/common/static/froala_editor_2.8.5/codemirror/codemirror-5.40.2/mode/xml/xml.js"></script><!-- Include Editor JS files. --> <script type="text/javascript" src="${ctx }/common/static/froala_editor_2.8.5/js/froala_editor.pkgd.min.js"></script> <!--中文字體包,注意要放在最下面,不然會報錯--> <script type="text/javascript" src="${ctx }/common/static/froala_editor_2.8.5/js/languages/zh_cn.js"></script> <script type="text/javascript">$(function (){//超大屏幕的功能按鈕var toolbarButtons = ['fullscreen', 'bold', 'italic', 'underline', 'strikeThrough', 'subscript', 'superscript', 'fontFamily', 'fontSize', '|', 'color', 'emoticons', 'inlineStyle', 'paragraphStyle', '|', 'paragraphFormat', 'align', 'formatOL', 'formatUL', 'outdent', 'indent', 'quote', 'insertHR', '-', 'insertLink', 'insertImage', 'insertVideo', 'insertFile', 'insertTable', 'undo', 'redo', 'clearFormatting', 'selectAll', 'html'];//大屏幕的功能按鈕var toolbarButtonsMD = ['fullscreen', 'bold', 'italic', 'underline', 'fontFamily', 'fontSize', 'color', 'paragraphStyle', 'paragraphFormat', 'align', 'formatOL', 'formatUL', 'outdent', 'indent', 'quote', 'insertHR', 'insertLink', 'insertImage', 'insertVideo', 'insertFile', 'insertTable', 'undo', 'redo', 'clearFormatting'];//小屏幕的功能按鈕var toolbarButtonsSM = ['fullscreen', 'bold', 'italic', 'underline', 'fontFamily', 'fontSize', 'insertLink', 'insertImage', 'insertTable', 'undo', 'redo'];//手機的功能按鈕var toolbarButtonsXS = ['bold', 'italic', 'fontFamily', 'fontSize', 'undo', 'redo'];//var pid = $('#pid').val();//編輯器初始化并賦值$('#edit').on('froalaEditor.initialized', function (e, editor) {$('#edit').froalaEditor('html.set','${article.article_content}');}).froalaEditor({placeholderText: '請輸入內(nèi)容', //默認填充內(nèi)容charCounterCount : true,//默認 顯示字數(shù)saveInterval : 0,//不自動保存,默認10000,0為不自動保存//theme : "dark",//主題:dark,red,gray,royal,注意需要引入對應(yīng)主題的cssheight : "600px",toolbarBottom : false,//默認toolbarButtonsMD : toolbarButtonsMD,toolbarButtonsSM : toolbarButtonsSM,toolbarButtonsXS : toolbarButtonsXS,toolbarInline : false,//true選中設(shè)置樣式,默認falseimageUploadMethod : 'POST',heightMin: 450,charCounterMax: 3000, //最大字數(shù)限制,-1為不限制saveURL: '${ctx}/webmana/article/saveArticle', //自動保存的地址(body參數(shù)為html內(nèi)容)saveParams: { postId: '1'}, //保存內(nèi)容時傳的參數(shù)spellcheck: false, //是否允許瀏覽器對輸入內(nèi)容進行拼寫檢查imageUploadURL: '${ctx}/webmana/attachment/uploadArticleImg',//上傳到本地服務(wù)器//imageUploadParams: {pid: '1'}, //上傳圖片時帶的參數(shù)///imageDefaultWidth: 100, //上傳圖片后的默認大小//imageResizeWithPercent: true,//不設(shè)置這個,imageDefaultWidth的單位為像素,設(shè)置后為%videoUploadURL:'${ctx}/webmana/attachment/uploadArticleVideo',enter: $.FroalaEditor.ENTER_BR, //設(shè)置回車鍵功能language: 'zh_cn',// toolbarButtons: ['bold', 'italic', 'underline', 'paragraphFormat', 'align','color','fontSize','insertImage','insertTable','undo', 'redo']});})function saveArticle(){var html=$('#edit').froalaEditor('html.get', true); //返回富文本編輯里面的html代碼$.ajax({type: 'POST',url: '${ctx}/webmana/article/saveArticle',dataType: 'json',data:{"articleName":$("#articleName").val(),"body":html,"articleId":$("#articleId").val()},success: function(data){if(data.success){layer.msg("保存成功", {icon: 1, time: 1500},function(){window.parent.location.reload();});}else{layer.msg("保存失敗", {icon: 1, time: 1500},function(){window.parent.location.reload();});}},error:function(data) {//console.log(data.msg);},});}</script></body>代碼里面比較說的比較清楚了,插件默認按鈕是英文title,引入中文包并設(shè)置就成為中文了,下面先總結(jié)幾個比較重要的點
1.初始化:
$('#edit').froalaEditor({})
2.自動保存:
saveURL為自動保存地址,如果需要就設(shè)置為點擊保存相同的地址即可
3.保存時傳入?yún)?shù)
saveParams: { postId: '1'} 在這個參數(shù)中可以放入保存文章時順帶往后臺傳的參數(shù)
4.圖片上傳路徑
imageUploadURL 如果要圖片上傳功能,則這個路徑必須寫,路徑為保存圖片的路徑,上傳圖片時的參數(shù)在imageUploadParams中寫。
注意:后臺保存圖片需要返回給前臺圖片的路徑,而且格式必須是這樣的
附j(luò)ava后臺上傳圖片方法:
// 上傳文章圖片@RequestMapping(value = "uploadArticleImg", method = RequestMethod.POST, produces = "application/json;charset=utf-8")@ResponseBodypublic String uploadArticleImg(@RequestParam(value = "file") MultipartFile file, //這樣接收文件@RequestParam Map<String,String> params,HttpServletRequest request) {Map<String,Object> ret=new HashMap<String, Object>();try {String path="/attachments/articleImages/";Map<String,String> name=uploadFile(path,file, request);ret.put("link","http://" + request.getServerName() //服務(wù)器地址+ ":"+ request.getServerPort() +path+name.get("saveName"));// 返回前臺return JSON.toJSONString(ret);} catch (Exception e) {e.printStackTrace();return JSON.toJSONString("fail");}}public Map<String,String> uploadFile(String path,MultipartFile file, HttpServletRequest request) throws IOException {Map<String,String> result=new HashMap<String,String>();String fileName = file.getOriginalFilename();//String basePath=request.getSession().getServletContext().getRealPath("/");// path=basePath+path; //設(shè)置文件保存路徑 // File tempFile = new File(path, new Date().getTime() + String.valueOf(fileName));String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();String saveName=String.valueOf((new Date()).getTime()).substring(8)+(int)((Math.random()*999+1))+'.'+fileType;File tempFile = new File(basePath+path, String.valueOf(saveName));if (!tempFile.getParentFile().exists()) { //創(chuàng)建文件夾tempFile.getParentFile().mkdir();}if (!tempFile.exists()) {tempFile.createNewFile();}file.transferTo(tempFile);result.put("fileName",fileName);result.put("saveName",saveName);return result;}5.視頻上傳
videoUploadURL在這個參數(shù)中寫視頻的上傳路徑,方法與上傳圖片相同
6.獲取編輯完成生成的代碼:
var html=$('#edit').froalaEditor('html.get', true); //返回富文本編輯里面的html代碼提交時就把這個html提交后臺即可,獲取的文本是有行內(nèi)樣式的html標(biāo)簽,如下,如果要展示文章,直接將html賦值給一個div就可以完全復(fù)原
標(biāo)題<br><img src="http://localhost:8081/attachments/articleImages/47321141.jpg" style="width: 515px;" class="fr-fic fr-dib"><br><span class="fr-video fr-dvb fr-draggable" contenteditable="false" draggable="true"><video class="fr-draggable fr-fvc fr-dvi" controls="" src="http://localhost:8081/attachments/articleVideos/23907698.mp4" style="width: 1145px; height: 522px;">Your browser does not support HTML5 video.</video></span>7.點擊編輯按鈕時將舊數(shù)據(jù)放進編輯中
$('#edit').on('froalaEditor.initialized', function (e, editor) {$('#edit').froalaEditor('html.set','獲取的html文本');}).froalaEditor({})加一個'froalaEditor.initialized',在里面用$('#edit').froalaEditor('html.set','獲取的html文本') 即可
8.手機端展示最好把上傳的圖片視頻默認為寬度100%
一般圖片上傳后會將你調(diào)整后的圖片寬度以px為單位存入后臺,但是有時我們需要圖片寬度為100%,則需要設(shè)置
imageDefaultWidth和imageResizeWithPercent:true參數(shù) 不設(shè)置imageResizeWithPercent,imageDefaultWidth的單位為像素,設(shè)置后為%9.破解
注意,因為此編輯器有個版權(quán)問題,在本機自己練習(xí)時正常,但程序部署到服務(wù)器時使用編輯時,會在編輯器內(nèi)出現(xiàn)一行紅色背景的字,提醒你版權(quán)問題,影響用戶體驗
解決辦法:
.fr-wrapper > div[style*='z-index: 9999'] {position: absolute;top: -10000px;opacity: 0;display: none;}在使用頁加上上述css就行了,版權(quán)提醒去無蹤
*僅限個人學(xué)習(xí)使用,商用的話還是購買下版權(quán)吧
?
總結(jié)
以上是生活随笔為你收集整理的超好用的富文本编辑器froalaEditor(方便传图片和视频等)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Github项目推荐|可视化 GAN 的
- 下一篇: 集成电路史上著名的十个人,有几个中国人?