基于jQuery的富文本编辑器summernote插件的使用教程
基于jQuery的富文本编辑器summernote插件的使用教程
一:最近项目中遇到使用富文本编辑器的功能, JQuery的富文本编辑器第一次使用。我在网上看了很多编辑器插件。下面我就说说我使用的这个summernote.js插件。
使用步骤
-
下载summernote.js ,这里我简单说一下主要文件;
下载链接:https://download.csdn.net/download/jiaohuang2442/15558876
dist文件夹内:
当然summernote.js 是必须引入的。还有这个插件的自带样式文件summernote.css
js文件夹内:因为summernote.js是基于jQuery和bootstrap的一个插件,所以项目中需要引入这两个文件。
这里有一个很重要的文件,在summernote\dist\lang里面的summernote-zh-CN.js(相当于设置编辑器中文) ;因为这个插件是英文的,如果你项目中不引入这个js文件,那你的编辑器设置栏会是英文的。
-
上面讲了重要文件,下面我直接上代码。先在项目需要此插件的页面中引入这些重要文件;
注意:路径根据自己文件来写
<link rel ="stylesheet" type ="text/css" href ="/media/summernote/dist/summernote.css" />
<script type="text/javascript" src="/media/summernote/js/bootstrap.min.js"></script>
<script type="text/javascript" src="/media/summernote/dist/summernote.js"></script>
<script type="text/javascript" src="/media/summernote/dist/lang/summernote-zh-CN.js"></script>
- 在dom中直接写一个容器就行,这里注意一点,给盒子设置一个ID;
<div id="summernote"></div>
- js代码;
<script>
$(document).ready(function () {
$('#summernote').summernote({
height: 500,
width:1000,
minHeight: 300,
maxwidth: 1000,
minwidth: 200,
maxHeight: 500,
focus: false,
// summernote自定义配置
toolbar: [
['operate', ['undo','redo']],
['magic',['style']],
['style', ['bold', 'italic', 'underline', 'clear']],
['para', ['height','fontsize','ul', 'ol', 'paragraph']],
['font', ['strikethrough', 'superscript', 'subscript']],
['insert',['hr']],
['layout',['fullscreen']],
],
callbacks: {
onImageUpload: function (files, editor) {
var $files = $(files);
// 通过each方法遍历每一个file
$files.each(function () {
var file = this;
// FormData,新的form表单封装,具体可百度,但其实用法很简单,如下
var data = new FormData();
// 将文件加入到file中,后端可获得到参数名为“file”
data.append("file", file);
// ajax上传
$.ajax({
data: data,
type: "POST",
url: "../../ashx_html/summernote.ashx",// div上的action
cache: false,
contentType: false,
processData: false,
// 成功时调用方法,后端返回json数据
success: function (response) {
console.log(response)
var json = $.parseJSON(response)
if (json.state == "error") {
alert("上传失败")
} else {
// 插入到summernote
$('#summernote').summernote('insertImage', json.img_url);
}
},
});
})
}
}
});
});
</script>
我们预览一下效果: