最近项目有个文章管理功能,我对比了很多富文本编辑器,有的是上传图片不方便,有的是复制粘贴不方便,有的是但编辑器里面不能改变图片大小,最后,我找到了froalaEditor,可以说是集各种功能为一身,不但界面清爽,功能也十分全面,插入图片和视频都很方便,自己可以到官网体验一下:https://www.froala/wysiwyg-editor
官方文档地址:https://www.froala/wysiwyg-editor/docs
由于官方提供的下载包没有第三方插件,不太全,所以自己整理了全面的插件
插件下载地址:
https://download.csdn/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>创建文章</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="输入文章标题" 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: '请输入内容', //默认填充内容
charCounterCount : true,//默认 显示字数
saveInterval : 0,//不自动保存,默认10000,0为不自动保存
//theme : "dark",//主题:dark,red,gray,royal,注意需要引入对应主题的css
height : "600px",
toolbarBottom : false,//默认
toolbarButtonsMD : toolbarButtonsMD,
toolbarButtonsSM : toolbarButtonsSM,
toolbarButtonsXS : toolbarButtonsXS,
toolbarInline : false,//true选中设置样式,默认false
imageUploadMethod : 'POST',
heightMin: 450,
charCounterMax: 3000, //最大字数限制,-1为不限制
saveURL: '${ctx}/webmana/article/saveArticle', //自动保存的地址(body参数为html内容)
saveParams: { postId: '1'}, //保存内容时传的参数
spellcheck: false, //是否允许浏览器对输入内容进行拼写检查
imageUploadURL: '${ctx}/webmana/attachment/uploadArticleImg',//上传到本地服务器
//imageUploadParams: {pid: '1'}, //上传图片时带的参数
///imageDefaultWidth: 100, //上传图片后的默认大小
//imageResizeWithPercent: true,//不设置这个,imageDefaultWidth的单位为像素,设置后为%
videoUploadURL:'${ctx}/webmana/attachment/uploadArticleVideo',
enter: $.FroalaEditor.ENTER_BR, //设置回车键功能
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,引入中文包并设置就成为中文了,下面先总结几个比较重要的点
1.初始化:
$('#edit').froalaEditor({})
2.自动保存:
saveURL为自动保存地址,如果需要就设置为点击保存相同的地址即可
3.保存时传入参数
saveParams: { postId: '1'} 在这个参数中可以放入保存文章时顺带往后台传的参数
4.图片上传路径
imageUploadURL 如果要图片上传功能,则这个路径必须写,路径为保存图片的路径,上传图片时的参数在imageUploadParams中写。
注意:后台保存图片需要返回给前台图片的路径,而且格式必须是这样的
附java后台上传图片方法:
// 上传文章图片
@RequestMapping(value = "uploadArticleImg", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@ResponseBody
public 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() //服务器地址
+ ":"
+ 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; //设置文件保存路径
// 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()) { //创建文件夹
tempFile.getParentFile().mkdir();
}
if (!tempFile.exists()) {
tempFile.createNewFile();
}
file.transferTo(tempFile);
result.put("fileName",fileName);
result.put("saveName",saveName);
return result;
}
5.视频上传
videoUploadURL在这个参数中写视频的上传路径,方法与上传图片相同
6.获取编辑完成生成的代码:
var html=$('#edit').froalaEditor('html.get', true); //返回富文本编辑里面的html代码
提交时就把这个html提交后台即可,获取的文本是有行内样式的html标签,如下,如果要展示文章,直接将html赋值给一个div就可以完全复原
标题<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.点击编辑按钮时将旧数据放进编辑中
$('#edit').on('froalaEditor.initialized', function (e, editor) {
$('#edit').froalaEditor('html.set','获取的html文本');
})
.froalaEditor({})
加一个'froalaEditor.initialized',在里面用$('#edit').froalaEditor('html.set','获取的html文本') 即可
8.手机端展示最好把上传的图片视频默认为宽度100%
一般图片上传后会将你调整后的图片宽度以px为单位存入后台,但是有时我们需要图片宽度为100%,则需要设置
imageDefaultWidth和imageResizeWithPercent:true参数
不设置imageResizeWithPercent,imageDefaultWidth的单位为像素,设置后为%
9.破解
注意,因为此编辑器有个版权问题,在本机自己练习时正常,但程序部署到服务器时使用编辑时,会在编辑器内出现一行红色背景的字,提醒你版权问题,影响用户体验
解决办法:
.fr-wrapper > div[style*='z-index: 9999'] {
position: absolute;
top: -10000px;
opacity: 0;
display: none;
}
在使用页加上上述css就行了,版权提醒去无踪
*仅限个人学习使用,商用的话还是购买下版权吧
更多推荐
超好用的富文本编辑器froalaEditor(方便传图片和视频等)
发布评论