安装
需要 HTML5 文档类型声明
Bootstrap 使用某些 HTML 元素和 CSS 属性,这些属性需要 HTML5 doctype。请在所有项目的开头包含 <!DOCTYPE html> 。
<!DOCTYPE html>
<html lang="en">
...
</html>
包含 js/css
Summernote 使用开源库 jQuery 和 Bootstrap,如果您使用 Summernote 的 Bootstrap 3 或 4 版本,或者使用 Lite 版本的 Summernote 则仅使用 jQuery。请在您的 HTML 页面的 head 区域包含以下代码。
<!-- include libraries(jQuery, bootstrap) -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<!-- include summernote css/js -->
<link href="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote.min.js"></script>
如果您将 Summernote 下载到不同的文件夹中,别忘了更改文件路径。
你可以,而且现在很多开发者都这样做,是在页面的 head 区域中包含样式表,并在页面的底部包含 JavaScript,但在关闭 body 标签之前。
Fontawesome 依赖
从 v0.8.0 版本开始,您不需要包含 fontawesome 来显示 Summernote 的图标。但您仍然可以使用 fontawesome 来创建自定义图标。有关详细信息,请访问自定义按钮部分。从 v0.8.18 版本开始,您有使用自定义图标覆盖 summernote 图标的能力。有关详细信息,请访问自定义图标部分。
嵌入
Summernote 可以使用或不用 form 。
要不用 form 使用,我们建议在 body 中使用一个 div ;这个元素将用于您希望 Summernote 编辑器在页面中渲染的位置。
<div id="summernote">Hello Summernote</div>
在 form 中使用,与上面几乎相同,但不是使用 div ,我们建议在 form 内使用一个 textarea 元素,该元素应包含一个名称属性,以便在表单提交时,您可以使用该名称在您的后端处理编辑器的数据。另外,如果要在 form 中使用 Summernote 设置属性 method="post" 以允许更大的编辑器内容解析到后端,如果不这样做,您的数据可能无法解析,或者将被截断。
<form method="post">
<textarea id="summernote" name="editordata"></textarea>
</form>
运行 summernote
当文档准备就绪时运行以下脚本!
$(document).ready(function() {
$('#summernote').summernote();
});
$(document).ready 函数特别必要,如果您在文档末尾包含 JavaScript。
简单示例
您也可以测试运行示例。将以下代码保存为 index.html ,然后用浏览器打开它。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Summernote</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote.min.js"></script>
</head>
<body>
<div id="summernote"><p>Hello Summernote</p></div>
<script>
$(document).ready(function() {
$('#summernote').summernote();
});
</script>
</body>
</html>
针对 Bootstrap 4
您还可以使用 Summernote 配合 Bootstrap 4,使用 summernote-bs4.js 和 summernote-bs4.css 。
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Summernote with Bootstrap 4</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote-bs4.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote-bs4.min.js"></script>
</head>
<body>
<div id="summernote"></div>
<script>
$('#summernote').summernote({
placeholder: 'Hello Bootstrap 4',
tabsize: 2,
height: 100
});
</script>
</body>
</html>
针对 bootstrap 5
您还可以使用 Summernote 配合 Bootstrap 5,使用 summernote-bs5.js 和 summernote-bs5.css 。
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Summernote with Bootstrap 5</title>
<!-- include libraries(jQuery, bootstrap) -->
<script type="text/javascript" src="//code.jquery.com/jquery-3.6.0.min.js"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" />
<script type="text/javascript" src="cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<!-- include summernote css/js-->
<link href="summernote-bs5.css" rel="stylesheet">
<script src="summernote-bs5.js"></script>
</head>
<body>
<div id="summernote"></div>
<script>
$('#summernote').summernote({
placeholder: 'Hello Bootstrap 5',
tabsize: 2,
height: 100
});
</script>
</body>
</html>
没有 Bootstrap(轻量版)
您可以使用 Summernote 而不使用 Bootstrap,使用 summernote-lite.js 和 summernote-lite.css 。
<html lang="en">
<head>
<meta charset="UTF-8">
<title>without bootstrap</title>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote-lite.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/summernote@0.9.0/dist/summernote-lite.min.js"></script>
</head>
<body>
<div id="summernote"></div>
<script>
$('#summernote').summernote({
placeholder: 'Hello stand alone ui',
tabsize: 2,
height: 120,
toolbar: [
['style', ['style']],
['font', ['bold', 'underline', 'clear']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['table', ['table']],
['insert', ['link', 'picture', 'video']],
['view', ['fullscreen', 'codeview', 'help']]
]
});
</script>
</body>
</html>
基础 API
初始化 Summernote
$('#summernote').summernote();
初始化 Summernote 并设置选项
高度和焦点
如果您设置了焦点选项,初始化 Summernote 后光标将聚焦到可编辑区域。
$('#summernote').summernote({
height: 300, // set editor height
minHeight: null, // set minimum height of editor
maxHeight: null, // set maximum height of editor
focus: true // set focus to editable area after initializing summernote
});
摧毁
摧毁 Summernote。
$('#summernote').summernote('destroy');
获取 & 设置代码
获取匹配元素集中第一个 summernote 的 HTML 内容。
var markupStr = $('#summernote').summernote('code');
如果初始化多个编辑器,您可以使用 jQuery eq 获取第二个 summernote 的 HTML 内容。
var markupStr = $('.summernote').eq(1).summernote('code');
设置为每个匹配元素内容的 HTML 字符串。
var markupStr = 'hello world';
$('#summernote').summernote('code', markupStr);
查看更多详情 API:使用 API 进行深入探究
销毁和代码
从 v0.7.0 版本开始,为了防止与其他 jQuery 库冲突,移除了直接使用 jQuery 方法 destroy 和 code 。您可以使用 summernote API 调用这些方法。
国际化支持
语言
包含带有语言文件的库。例如: summernote-ko-KR.js .
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link href="summernote.css" rel="stylesheet">
<script src="summernote.min.js"></script>
<!-- include summernote-ko-KR -->
<script src="lang/summernote-ko-KR.js"></script>
使用区域选项运行脚本。
$(document).ready(function() {
$('#summernote').summernote({
lang: 'ko-KR' // default: 'en-US'
});
});
集成
Django、Rails、Angular 等中可用的第三方库。
Django
Django 管理页面便捷更新。
- django-summernote
- Django Summernote 插件
React
使用 Summernote 与 React,你可以使用 react-summernote 包。
- react-summernote
初始化选项
通过初始化各种选项和模块来自定义。
自定义工具栏、弹出框
Summernote 允许您自定义工具栏。
$('#summernote').summernote({
toolbar: [
// [groupName, [list of button]]
['style', ['bold', 'italic', 'underline', 'clear']],
['font', ['strikethrough', 'superscript', 'subscript']],
['fontsize', ['fontsize']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['height', ['height']]
]
});
您可以使用预装按钮来组合工具栏。
- 插入
- picture : 打开图片对话框
- link : 打开链接对话框
- video : 打开视频对话框
- table : 插入表格
- hr : 插入水平线
- 字体样式
- fontname : 设置字体家族
- 设置字体大小
- 设置字体大小单位
- color : 设置前景色和背景色
- 设置前景色
- backcolor : 设置背景颜色
- 切换字体加粗
- italic : 切换斜体
- underline : 切换下划线
- strikethrough : 切换删除线
- superscript : 切换上标
- 切换下标
- 清除字体样式
- 段落样式
- style : 选择格式化块
- ol : 切换有序列表
- ul : 切换无序列表
- paragraph : 段落对齐下拉菜单
- height : 设置行间距
- 杂项
- fullscreen : 切换全屏编辑模式
- codeview : 切换所见即所得和 HTML 编辑模式
- undo : 撤销
- redo : 重做
- help : 打开帮助对话框
工具栏按钮的以下设置是默认选项。
toolbar: [
['style', ['style']],
['font', ['bold', 'underline', 'clear']],
['fontname', ['fontname']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['table', ['table']],
['insert', ['link', 'picture', 'video']],
['view', ['fullscreen', 'codeview', 'help']],
],
空气模式有自己的弹出窗口,而不是工具栏。您可以使用 popover.air 选项自定义它。
$('#summernote').summernote({
popover: {
air: [
['color', ['color']],
['font', ['bold', 'underline', 'clear']]
]
}
});
您也可以以相同的方式设置其他弹出窗口的按钮。以下设置是弹出窗口的默认选项。
popover: {
image: [
['image', ['resizeFull', 'resizeHalf', 'resizeQuarter', 'resizeNone']],
['float', ['floatLeft', 'floatRight', 'floatNone']],
['remove', ['removeMedia']]
],
link: [
['link', ['linkDialogShow', 'unlink']]
],
table: [
['add', ['addRowDown', 'addRowUp', 'addColLeft', 'addColRight']],
['delete', ['deleteRow', 'deleteCol', 'deleteTable']],
],
air: [
['color', ['color']],
['font', ['bold', 'underline', 'clear']],
['para', ['ul', 'paragraph']],
['table', ['table']],
['insert', ['link', 'picture']]
]
}
块引用断行级别
您可以使用 blockquoteBreakingLevel 选项设置引用块的分隔级别。
每个可配置的分隔级别意味着:
- 0 - 不分隔,新段落保持在引用内。
- 1 - 分隔祖先列表中的第一个引用块。
- 2 - 打破所有引用块,使新段落不被引用。(默认)
$('#summernote').summernote({
blockquoteBreakingLevel: 2
});
自定义样式
您可以使用 styleTags 选项设置自己的样式选择。
$('#summernote').summernote({
styleTags: [
'p',
{ title: 'Blockquote', tag: 'blockquote', className: 'blockquote', value: 'blockquote' },
'pre', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6'
],
});
标签可以通过标签名称指定(如上文的 p 或 pre 或 h1 - h6 )。还可以通过提供一个类似的对象来更详细地自定义样式:
{
tag : 'tag name ',
title : 'dropdown item title',
style : 'dropdown item style',
className : 'applyed element class name and dropdown item className',
value : 'Value to apply when clicked'
}
自定义字体名称
您可以使用 fontNames 选项定义字体名称项。
$('#summernote').summernote({
fontNames: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New']
});
Summernote 在添加到下拉列表之前会测试 fontNames 中的字体。在使用网络字体时,这是一个问题。很难选择一个合适的时间来检查网络字体的可用性。您可以使用 fontNamesIgnoreCheck 定义要忽略的网络字体列表。
$('#summernote').summernote({
fontNames: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Merriweather'],
fontNamesIgnoreCheck: ['Merriweather']
});
Summernote 会自动将当前 dom 元素上给出的可用字体填充到字体下拉列表中。如果您只想在下拉列表中显示特定的字体列表,可以将 addDefaultFonts 选项设置为 false ,并配合 fontNames 选项。以下示例设置将只添加 Arial 和 Arial Black 字体到下拉列表中。
$('#summernote').summernote({
fontNames: ['Arial', 'Arial Black'],
addDefaultFonts: false
});
自定义字体大小单位
您可以使用 fontSizeUnits 选项设置可用的字体大小单位。
$('#summernote').summernote({
fontSizeUnits: ['px', 'pt']
});
自定义行高
可以覆盖默认列表并指定一个自定义列表。
$('#summernote').summernote({
lineHeights: ['0.2', '0.3', '0.4', '0.5', '0.6', '0.8', '1.0', '1.2', '1.4', '1.5', '2.0', '3.0']
});
自定义占位符
可以使用 placeholder 选项定义一个占位符。
$('#summernote').summernote({
placeholder: 'write here...'
});
Summernote 也可以设置为从 dom 元素的 placeholder 属性继承占位符。
<div class="summernote" placeholder="first placeholder"></div>
<div class="summernote" placeholder="second placeholder"></div>
然后在初始化时将 inheritPlaceholder 选项设置为 true 。
$('.summernote').summernote({
inheritPlaceholder: true
});
对话框
对话框可以放置在 body 中,而不是 Summernote 内部。如果您在模态对话框中使用 Summernote,请将此选项设置为 true 。
$('#summernote').summernote({
dialogsInBody: true
});
默认情况下,对话框显示和隐藏没有淡入淡出效果。但您可以通过 dialogsFade 来开启它。
$('#summernote').summernote({
dialogsFade: true // Add fade effect on dialogs
});
禁用拖放
您可以使用 disableDragAndDrop 选项禁用拖放功能。
$('#summernote').summernote({
disableDragAndDrop: true
});
禁用快捷键
您可以使用 shortcuts 选项禁用自定义快捷键。
$('#summernote').summernote({
shortcuts: false
});
禁用 TAB
您可以使用 tabDisable 选项禁用 TAB/Shift+Tab 交互。这将允许在表单中通过 Tab 键切换字段。
$('#summernote').summernote({
tabDisable: false
});
CodeView 的 XSS 保护
Summernote 为 CodeView 提供了 XSS 保护。它包括过滤标签和 iframe 的白名单。
白名单过滤器默认开启,但标签过滤未开启。您可以通过以下选项开启或关闭它们。
$('#summernote').summernote({
codeviewFilter: false,
codeviewIframeFilter: true
});
您还可以添加自己的白名单域名并使用自定义标签过滤器。请在自定义前检查默认过滤器。
$('#summernote').summernote({
codeviewFilterRegex: 'custom-regex',
codeviewIframeWhitelistSrc: ['my-own-domainname']
});
但您必须记住,这种保护只影响前端 - 要彻底防止攻击,您还必须在后端再次检查。
基础 API
您可以使用 summernote .初始化 Summernote。
$('#summernote').summernote();
您可以通过 summernote 方法使用编辑器 API。这是一个插入“hello world”文本的示例代码。
$('#summernote').summernote('editor.insertText', 'hello world'));
它调用编辑器模块的 insertText 方法,参数为“hello world”。第一个参数是字符串类型,表示模块及其方法。其余的是方法参数。
如果您不提供模块名称调用 API,则会调用 editor.methodName 。
$('#summernote').summernote('insertText', 'hello world');
命名为 editor 的模块支持编辑器基本行为的多个方法。
代码视图
您可以通过 API 切换可编辑/可编码视图。
$('#summernote').summernote('codeview.toggle');
创建范围
为当前用户选择创建范围对象。
var range = $('#summernote').summernote('createRange');
禁用,启用
您可以通过 API 禁用编辑器。
$('#summernote').summernote('disable');
如果您想再次启用编辑器,请调用 API 并使用 enable 。
$('#summernote').summernote('enable');
禁用拼写检查
您可以使用 spellCheck 选项在编辑区域禁用拼写检查。
$('#summernote').summernote({
spellCheck: true
});
禁用 Grammarly 浏览器插件
您可以使用 disableGrammar 选项禁用 Grammarly 浏览器插件(目前正在研究其他语法插件以禁用其选项)。
$('#summernote').summernote({
disableGrammar: false
});
focus
在当前 summernote 中设置焦点
$('#summernote').summernote('focus');
全屏
您可以通过 API 切换全屏视图。
$('#summernote').summernote('fullscreen.toggle');
是否全屏
您可以通过使用 isFullscreen 来程序化地判断 Summernote 是否处于全屏模式,这将返回 true 或 false 。
$('#summernote').summernote('fullscreen.isFullscreen');
界面
您可以程序化地找到您正在使用的 Summernote。这将返回三个值之一: bs3 、 bs4 或 lite 。
$.summernote.interface;
是否为空
返回编辑器内容是否为空。
即使编辑器内容为空,编辑区域也需要 <p><br></p> 来聚焦。因此 Summernote 支持此方法以帮助检查编辑器内容是否为空。
if ($('#summernote').summernote('isEmpty')) {
alert('editor content is empty');
}
重置
清除编辑器内容并移除所有存储的历史记录。
$('#summernote').summernote('reset');
保存范围,恢复范围
saveRange 内部保存当前用户选择。
$('#summernote').summernote('saveRange');
restoreRange 恢复当前保存的范围
$('#summernote').summernote('saveRange');
// move cursor and select another
$('#summernote').summernote('restoreRange');
撤销,重做
撤销和重做上一个命令
$('#summernote').summernote('undo');
$('#summernote').summernote('redo');
字体样式 API
背景色,前景色
设置背景色或前景色。
// @param {String} color
$('#summernote').summernote('backColor', 'red');
// @param {String} color
$('#summernote').summernote('foreColor', 'blue');
粗体、斜体、下划线、删除线
设置字体样式。
$('#summernote').summernote('bold');
$('#summernote').summernote('italic');
$('#summernote').summernote('underline');
$('#summernote').summernote('strikethrough');
fontName
设置字体族。
// @param {String} fontName
$('#summernote').summernote('fontName', 'Arial');
字体大小
设置字体大小。
// @param {Number} font size - unit is determined by selected font size unit.
$('#summernote').summernote('fontSize', 20);
字体大小单位
设置字体大小单位。
// @param {String} font size unit - defaults to px.
$('#summernote').summernote('fontSizeUnit', 'pt');
删除格式
清除样式。
$('#summernote').summernote('removeFormat');
上标,下标
设置上标或下标。
$('#summernote').summernote('superscript');
$('#summernote').summernote('subscript');
段落 API
格式化 H1-H6
更改当前段落为 <h1> ~ <h6> 。
$('#summernote').summernote('formatH2');
$('#summernote').summernote('formatH6');
格式化段落
更改当前段落为 <p> 。
$('#summernote').summernote('formatPara');
缩进和缩出
在当前段落中缩进或缩出。
$('#summernote').summernote('indent');
$('#summernote').summernote('outdent');
插入有序列表
切换有序列表或无序列表
$('#summernote').summernote('insertOrderedList');
$('#summernote').summernote('insertUnorderedList');
插入段落
插入一个段落
$('#summernote').summernote('insertParagraph');
左对齐、右对齐等
设置段落的对齐方式。
$('#summernote').summernote('justifyLeft');
$('#summernote').summernote('justifyRight');
$('#summernote').summernote('justifyCenter');
$('#summernote').summernote('justifyFull');
行高
设置行高。
// @param {Number} line height - unit is px
$('#summernote').summernote('lineHeight', 20);
插入 API
创建链接,取消链接
创建链接和解链。
// @param {String} text - link text
// @param {String} url - link url
// @param {Boolean} isNewWindow - whether link's target is new window or not
$('#summernote').summernote('createLink', {
text: "This is the Summernote's Official Site",
url: 'http://summernote.org',
isNewWindow: true
});
$('#summernote').summernote('unlink');
插入图片
插入图片。
// @param {String} url
// @param {String|Function} filename - optional
$('#summernote').summernote('insertImage', url, filename);
您可以通过传递回调作为第二个参数来修改图像。
$('#summernote').summernote('insertImage', url, function ($image) {
$image.css('width', $image.width() / 3);
$image.attr('data-filename', 'retriever');
});
插入节点
插入一个元素或文本节点。
var node = document.createElement('div');
// @param {Node} node
$('#summernote').summernote('insertNode', node);
插入文本
插入文本。
// @param {String} text
$('#summernote').summernote('insertText', 'Hello, world');
粘贴 HTML
粘贴 HTML 字符串。
// @param {String} HTML string
var HTMLstring = '<div><p>Hello, world</p><p>Summernote can insert HTML string</p></div>';
$('#summernote').summernote('pasteHTML', HTMLstring);
范围与选择 API
保存范围
参考 #保存范围
恢复范围
参考 #恢复范围
获取最后范围
summernote 正在保存当前光标上的范围对象(WrappedRange)。
const rng = $('#summernote').summernote('editor.getLastRange');
当 summernote 通过 DOM 事件保存范围时
- keydown
- keyup
- focus
- mouseup
- paste
当 Summernote 通过 API 保存一个范围时
- editor.insertImage -> 图片
- editor.insertNode -> 节点
- editor.insertText -> 文本节点
- editor.pasteHTML -> 最后的内容节点
- editor.insertHorizontalRule -> hr 节点的下一个兄弟节点
- editor.createLink -> 链接节点
设置最后范围
您可以在 summernote 可编辑元素的节点中定义自定义范围。
const range = $.summernote.range; // range utility
// set my custom range
$('#summernote').summernote('editor.setLastRange', range.createFromNodeAfter(node).select());
range 实用工具
const range = $.summernote.range; // range utility
创建包装范围对象
范围实用工具创建包装范围类的实例
创建
从参数或浏览器选择创建包装范围对象
const rng = range.create(startContainer, startOffset, endContainer, endOffset)
// or
const rng = range.create() // is equals range.createFromSelection()
createFromNode
从节点创建包装范围对象
const rng = range.createFromNode(node)
从节点前创建
从节点前位置创建包装范围
const rng = range.createFromNodeBefore(node)
从节点后创建
从节点后位置创建包装范围
const rng = range.createFromNodeAfter(node)
从选择创建
从选择创建 WrappedRange 对象
const rng = range.createFromSelection(node)
包装范围对象
select()
选择更新可见范围
rng.select()
折叠(是否折叠到开始)
const newRng = rng.collapse(true); // to start rng
or
const newRng = rng.collapse(); // to end rng
分割文本()
在范围内分割文本
const textRng = rng.splitText()
deleteContents()
删除指定范围内的内容
const newRng = rng.deleteContents()
isCollapsed()
返回范围是否已折叠
const isCollapsed = rng.isCollapsed()
wrapBodyInlineWithPara()
将 body 的子节点包裹成段落
const newRng = rng.wrapBodyInlineWithPara()
插入节点(node)
在当前光标处插入节点
const node = rng.insertNode(document.createElement('div'))
pasteHTML(标记)
在当前光标处插入 HTML
const nodes = rng.pasteHTML(`<div>summernote</div>`)
toString()
返回范围文本
getWordRange(findAfter)
返回光标前(或后)单词的范围
const newRng = rng.getWordRange(); // before cursor
// or
const newRng = rng.getWordRange(true); // after cursor
getWordsMatchRange(regex)
返回光标前匹配正则表达式的单词范围
// range : 'hi @Peter Pan'
const rng = range.create() // or $('.summernote').summernote('getLastRange');
const newRng = rng.getWordsMatchRange(/@[a-z ]+/i)
console.log(newRng.toString()) // '@Peter Pan'
getClientRects()
返回表示屏幕占用范围的 DOMRect 对象列表。
Range.getClientRects()
https://developer.mozilla.org/en-US/docs/Web/API/Range/getClientRects
回调函数
支持 Summernote 初始化回调和 jQuery 的自定义事件风格回调。
在 v0.7.0 之后,回调函数在 options 中的位置发生了变化。
在 v0.7.0 之后,每个回调函数都应该被 callbacks 对象包装。
v0.6.5 之后回调函数仅适用于驼峰式字符串
小写字符串已用于基本事件名称(例如: oninit , onenter , onfocus , onblur , onkeyup , onkeydown , onpaste )。相比之下,高级功能的回调名称使用驼峰式字符串。这使用起来不一致且令人困惑。因此,我们将所有小写回调重命名为驼峰式字符串。
在命令之前
onBeforeCommand 回调在执行命令之前被调用。
发生变化时
- IE9-10: DOMCharacterDataModified, DOMSubtreeModified, DOMNodeInserted
- Chrome, FF:输入
// onChange callback
$('#summernote').summernote({
callbacks: {
onChange: function(contents, $editable) {
console.log('onChange:', contents, $editable);
}
}
});
// summernote.change
$('#summernote').on('summernote.change', function(we, contents, $editable) {
console.log('summernote\'s content is changed.');
});
代码视图变更时
WIP: 需要编写说明
onDialog 显示
WIP: 需要编写说明
onEnter
// onEnter callback
$('#summernote').summernote({
callbacks: {
onEnter: function() {
console.log('Enter/Return key pressed');
}
}
});
// summernote.enter
$('#summernote').on('summernote.enter', function() {
console.log('Enter/Return key pressed');
});
聚焦,失焦,失焦代码视图
// onFocus callback
$('#summernote').summernote({
callbacks: {
onFocus: function() {
console.log('Editable area is focused');
}
}
});
// summernote.focus
$('#summernote').on('summernote.focus', function() {
console.log('Editable area is focused');
});
// onBlur callback
$('#summernote').summernote({
callbacks: {
onBlur: function() {
console.log('Editable area loses focus');
}
}
});
// summernote.blur
$('#summernote').on('summernote.blur', function() {
console.log('Editable area loses focus');
});
// onBlurCodeview callback
$('#summernote').summernote({
callbacks: {
onBlurCodeview: function() {
console.log('Codeview area loses focus');
}
}
});
// summernote.blur.codeview
$('#summernote').on('summernote.blur.codeview', function() {
console.log('Codeview area loses focus');
});
onImageLinkInsert
覆盖通过 URL 插入图片
// onImageLinkInsert callback
$('#summernote').summernote({
callbacks: {
onImageLinkInsert: function(url) {
// url is the image url from the dialog
$img = $('<img>').attr({ src: url })
$summernote.summernote('insertNode', $img[0]);
}
}
});
// summernote.image.link.insert
$('#summernote').on('summernote.image.link.insert', function(we, url) {
// url is the image url from the dialog
$img = $('<img>').attr({ src: url })
$summernote.summernote('insertNode', $img[0]);
});
onImageUpload
覆盖图片上传处理程序(默认:在 IMG 标签上的 base64 数据 URL)。您可以将图片上传到服务器或 AWS S3:更多...
// onImageUpload callback
$('#summernote').summernote({
callbacks: {
onImageUpload: function(files) {
// upload image to server and create imgNode...
$summernote.summernote('insertNode', imgNode);
}
}
});
// summernote.image.upload
$('#summernote').on('summernote.image.upload', function(we, files) {
// upload image to server and create imgNode...
$summernote.summernote('insertNode', imgNode);
});
onImageUploadError
WIP: 需要编写说明
onInit
// onInit callback
$('#summernote').summernote({
callbacks: {
onInit: function() {
console.log('Summernote is launched');
}
}
});
// summernote.init
$('#summernote').on('summernote.init', function() {
console.log('Summernote is launched');
});
onKeyup, onKeydown
// onKeyup callback
$('#summernote').summernote({
callbacks: {
onKeyup: function(e) {
console.log('Key is released:', e.keyCode);
}
}
});
// summernote.keyup
$('#summernote').on('summernote.keyup', function(we, e) {
console.log('Key is released:', e.keyCode);
});
// onKeydown callback
$('#summernote').summernote({
callbacks: {
onKeydown: function(e) {
console.log('Key is downed:', e.keyCode);
}
}
});
// summernote.keydown
$('#summernote').on('summernote.keydown', function(we, e) {
console.log('Key is downed:', e.keyCode);
});
鼠标按下,鼠标抬起
粘贴
// onPaste callback
$('#summernote').summernote({
callbacks: {
onPaste: function(e) {
console.log('Called event paste');
}
}
});
// summernote.paste
$('#summernote').on('summernote.paste', function(e) {
console.log('Called event paste');
});
滚动
WIP: 需要编写说明
自定义按钮
Summernote 还支持自定义按钮。如果您想创建自己的按钮,您只需定义并使用选项即可。
定义按钮
您可以使用$.summernote.ui 创建按钮对象。这些按钮对象具有以下属性。
- contents: 按钮上显示的内容
- tooltip: 鼠标悬停时的提示文本
- click: 鼠标点击时调用的回调函数
以下代码是关于插入文本“hello”的简单按钮
var HelloButton = function (context) {
var ui = $.summernote.ui;
// create button
var button = ui.button({
contents: '<i class="fa fa-child"/> Hello',
tooltip: 'hello',
click: function () {
// invoke insertText method with 'hello' on editor module.
context.invoke('editor.insertText', 'hello');
}
});
return button.render(); // return button as jquery object
}
您可以看到 render() ,它返回一个按钮 jQuery 对象。
使用带有选项的按钮
让我们学习如何在工具栏上使用按钮。
首先,您可以使用名为 buttons 的选项定义按钮,它是一组键值对。您可以在工具栏选项中定义自定义按钮。
$('.summernote').summernote({
toolbar: [
['mybutton', ['hello']]
],
buttons: {
hello: HelloButton
}
});
您也可以用同样的方式使用自定义按钮 popover 。
自定义图标
Summernote 支持使用您自己的自定义图标。例如,您可以使用基于 SVG 的图标而不是默认图标。
定义您自己的图标
如果您想覆盖默认图标,请按如下方式配置 summernote:
$('.summernote').summernote({
icons: {
align: '<svg [...]>[...]</svg>',
// [...]
}
});
模块系统
为了支持可扩展功能,summernote 是通过模块系统构建的。此模块系统是受 spring 框架启发的。
关键术语
- 模块:模块是一个组件。
- 上下文:上下文是一种容器。它包含模块和编辑器状态。
- 渲染器:渲染器是创建元素的函数。
- UI:UI 是一组用于构建 UI 元素的渲染器。
模块
模块是实现功能的组件,它具有生命周期。模块还具有与生命周期相关的方法或辅助方法。
初始化
当通过$(‘..’).summernote();初始化编辑器时,将调用此方法。您可以在编辑器元素上附加事件和创建的元素(例如,可编辑的,……)。
this.initialize = function () {
// create button
var button = ui.button({
className: 'note-btn-bold',
contents: '<i class="fa fa-bold">',
click: function (e) {
context.invoke('editor.bold'); // invoke bold method of a module named editor
}
});
// generate jQuery element from button instance.
this.$button = button.render();
$toolbar.append(this.$button);
}
销毁
当编辑器被$(‘..’).summernote(‘destroy’);销毁时,将调用此方法。您应该在 initialize 上断开事件并移除元素。
this.destroy = function () {
this.$button.remove();
this.$button = null;
}
应初始化
此方法用于决定模块是否初始化。
// AirPopover's shouldInitialize
this.shouldInitialize = function () {
return options.airMode && !list.isEmpty(options.popover.air);
};
以下是 AutoLink 模块的完整代码。
// Module Name is AutoLink
// @param {Object} context - states of editor
var AutoLink = function (context) {
// you can get current editor's elements from layoutInfo
var layoutInfo = context.layoutInfo;
var $editor = layoutInfo.editor;
var $editable = layoutInfo.editable;
var $toolbar = layoutInfo.toolbar;
// ui is a set of renderers to build ui elements.
var ui = $.summernote.ui;
// this method will be called when editor is initialized by $('..').summernote();
// You can attach events and created elements on editor elements(eg, editable, ...).
this.initialize = function () {
// create button
var button = ui.button({
className: 'note-btn-bold',
contents: '<i class="fa fa-bold">',
click: function (e) {
// invoke bold method of a module named editor
context.invoke('editor.bold');
}
});
// generate jQuery element from button instance.
this.$button = button.render();
$toolbar.append(this.$button);
}
// this method will be called when editor is destroyed by $('..').summernote('destroy');
// You should detach events and remove elements on `initialize`.
this.destroy = function () {
this.$button.remove();
this.$button = null;
}
};
更多模块示例:模块
带有选项的模块
您可以定义带有选项的自定义模块。
$(".summernote").summernote({
modules: {
myModule: MyModule
}
});
可以使用外部 API 调用模块的方法。
$(".summernote").summernote("myModule.method", 'hello');
插件
插件是一种外部模块。您也可以使用插件定义自己的模块。
// src/mymodule.js
$.extend($.summernote.plugins, {
myModule: function (context) {
// define module
// ...
}
});
以下链接是外部模块的示例。
- plugin-hello
插件经过新模块系统重新设计,在 v0.7.0 之后
旧插件难以控制编辑状态(例如,范围、布局等)。在 v0.7.0 之后,插件通过新模块系统重新设计。它与模块完全相同,只是周围模块模式不同。
模块
通知/信息区域
Summernote 允许添加带有上下文着色的通知,以指示通知类型,或用于信息目的。
在正常模式下使用 Summernote 时,该区域出现在底部,而在 Air 模式下使用时,则位于编辑区域顶部。
使用通知区域很简单,可以通过指定其类名 .note-status-output 来使用该区域。
通知元素可以使用任何标记,但我们增加了一些类似于 Bootstrap 警报的样式。例如,要生成错误或危险警报,您可以使用 <div class="alert alert-danger">This is an error</div> 。您还可以使用 alert-info , alert-warning , alert-success 和 alert-danger 。
您可以使用 jQuery 或其他 JavaScript 方法通过定位输出元素添加上述消息,例如(使用 jQuery):
$('.note-status-output').html(
'<div class="alert alert-danger">' +
'This is an error using a Bootstrap alert that has been restyled to fit here.' +
'</div>'
);
如果您只想显示信息性文本,您也可以添加不带警报的文本,如果您愿意的话。
$('.note-status-output').html(
'Text Information'
);
您还可以通过将文本放置在 div , span 或 small 元素内并将类 .pull-right 包含在内来将文本放置在右侧。
您还可以使用上下文颜色为您的文本添加样式,使用类 text-muted , text-primary ,‘text-success’, text-info , text-warning 和 text-danger 。
发表留言 取消回复