summernote富文本编辑器的基本使用

来源:互联网 发布:如何打开445端口 编辑:程序博客网 时间:2024/05/17 02:50

summernote富文本编辑器的基本使用(一)
本文主要是跟官网的一些翻译,也锻炼下英语水平。原英文网址http://summernote.org/getting-started/

基础API

初始化 summernote

$('#summernote').summernote();

初始化并配置summernote

高度和焦点设置

如果对summernote设置了focus项,在编辑器初始化之后会自动获取焦点。

$('#summernote').summernote({

 height: 300,                 // set editor height

  minHeight:null,             // set minimum heightof editor

  maxHeight:null,             // set maximum heightof editor

  focus: true                  // set focus to editable areaafter initializing summernote

});

对高度进行设置后,如果内容超过编辑器高度会出现滚动条。否则,编辑器高度会随内容高度变化而变化。

编辑器的销毁(destroy)

销毁summernote

$('#summernote').summernote('destroy');

获取&设置HTML内容(get&set)

获取编辑器内的HTML内容

var markupStr = $('#summernote').summernote('code');

如果初始化了多个编辑器,可以通过jquery的eq方法获取某个编辑器的HTML内容。eg,获取第二个编辑器的。

var markupStr = $('.summernote').eq(1).summernote('code');

给指定的编辑器设置HTML内容

var markupStr = 'hello world';

$('#summernote').summernote('code', markupStr);

国际化支持

语言

引入需要支持的语言库。eg. summernote-ko-KR.js

<linkhref="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css"rel="stylesheet">

<scriptsrc="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>

<scriptsrc="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>

 

<link href="summernote.css"rel="stylesheet">

<script src="summernote.min.js"></script>

 

<!-- include summernote-ko-KR -->

<scriptsrc="lang/summernote-ko-KR.js"></script>

通过本地配置运行引入的脚本

$(document).ready(function() {

 $('#summernote').summernote({

    lang: 'ko-KR' // default: 'en-US'

 });

});

初始化配置

通过配置option和组件来自定义编辑器

自定义工具栏,弹出框

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']]
  ]
});

你也可以使用插件中已经预先定义好的工具栏。
你可以使用popover.air项来自定义极简模式的弹出框而不是工具栏。

$('#summernote').summernote({
  popover: {
    air: [
      ['color', ['color']],
      ['font', ['bold', 'underline', 'clear']]
    ]
  }
});

同样也可以配置其他弹出框的按钮。

自定义placeholder

$('#summernote').summernote({
  placeholder: 'write here...'
});

自定义字体

$('#summernote').summernote({
  fontNames: ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New']
});

summernote在把配置项中的字体添加到字体下拉框之前会先进行字体检测,因此当我们使用网络字体时会遇到问题。可以在fontNamesIgnoreCheck配置项中定义网络字体的列表来使编辑器忽略对网络字体的检测。

Dialogs

对话框不止可以放置在编辑器内,也可以被置于body中。

$('#summernote').summernote({
  dialogsInBody: true
});

Dialogs默认是没有淡入淡出效果的,可以使用dialogsFade配置

$('#summernote').summernote({
  dialogsFade: true  // Add fade effect on dialogs
});

禁止拖放

可以使用disableDragAndDrop禁止拖放

$('#summernote').summernote({
  disableDragAndDrop: true
});

禁止使用快捷键

$('#summernote').summernote({
  shortcuts: false
});

基础API(editor模块)

使用summernote初始化编辑器

$('#summernote').summernote();

然后可以使用summernote调用编辑器提供的API。下面是一个插入文本的示例代码。

$('#summernote').summernote('editor.insertText', 'hello world'));

它调用了editor模块的‘insertText’函数,第一个参数是代表模块及其方法的字符串,其余的是需要传入方法的参数。
第一个参数没有模块名的情况下,会默认为editor。

$('#summernote').summernote('insertText', 'hello world');

editor模块中支持以下方法

createRange

为用户当前选中的内容创建一个范围对象。

var range = $('#summernote').summernote('createRange');

saveRange, restoreRange

保存当前用户选中的内容

$('#summernote').summernote('saveRange');

重新保存选中的区域

$('#summernote').summernote('saveRange');

// move cursor and select another

$('#summernote').summernote('restoreRange');

undo, redo

撤销和恢复最后一个命令

$('#summernote').summernote('undo');

$('#summernote').summernote('redo');

focus

为编辑器设置焦点

$('#summernote').summernote('focus');

isEmpty

返回编辑器中内容是否为空
编辑区域获取焦点时会自动生成

 

,即使并没有实际内容。所以summernote提供了这个方法来判断内容是否真的为空。

if ($('#summernote').summernote('isEmpty')) {

 alert('contents is empty');

}

reset(重置)

清除内容和存储记录

$('#summernote').summernote('reset');

disable, enable

disable使编辑器处于不可用状态。

$('#summernote').summernote('disable');

调用enable可以使编辑器从不可以转换到可用状态。

$('#summernote').summernote('enable');

字体样式API

bold, italic, underline, strikethrough

设置编辑器所有内容的字体样式。

$('#summernote').summernote('bold');//加粗

$('#summernote').summernote('italic');//斜体

$('#summernote').summernote('underline');//下划线

$('#summernote').summernote('strikethrough');//删除线

superscript, subscript(上角标,下角标)

$('#summernote').summernote('superscript');

$('#summernote').summernote('subscript');

removeFormat(清除样式)

$('#summernote').summernote('removeFormat');

backColor, foreColor(背景色,前景色)

// @param {String} color

$('#summernote').summernote('backColor', 'red');

 

// @param {String} color

$('#summernote').summernote('foreColor', 'blue');

fontName(字体)

// @param {String} fontName

$('#summernote').summernote('fontName', 'Arial');

fontSize(字体大小)

// @param {Number} font size - unit is px

$('#summernote').summernote('fontSize', 20);

Paragraph API

justify left, right and more

设置段落居中样式

$('#summernote').summernote('justifyLeft');

$('#summernote').summernote('justifyRight');

$('#summernote').summernote('justifyCenter');

$('#summernote').summernote('justifyFull');

insertParagraph(插入段落)

$('#summernote').summernote('insertParagraph');

insertOrderedList(插入列表)

$('#summernote').summernote('insertOrderedList');

$('#summernote').summernote('insertUnorderedList');

indent and outdent(缩进和凸排)

$('#summernote').summernote('indent');

$('#summernote').summernote('outdent');

formatPara

将编辑器内容格式化为段落

$('#summernote').summernote('formatPara');

formatH1-H6

$('#summernote').summernote('formatH2');

$('#summernote').summernote('formatH6');

lineHeight(设置行高)

// @param {Number} line height - unit is px

$('#summernote').summernote('lineHeight', 20);

Insertion API

insertImage(插入图片)

// @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');

});

insertNode

插入元素和文本节点

var node =document.createElement('div');

// @param {Node} node

$('#summernote').summernote('insertNode', node);

insertText(插入文本)

// @param {String} text

$('#summernote').summernote('insertText', 'Hello, world');

createLink, unlink(创建、取消链接)

// @param {String} text - link text

// @param {String} url - link url

// @param {Boolean} newWindow - whether link's target isnew window or not

$('#summernote').summernote('createLink', {

 text: 'This is the Summernote's Official Site',

  url: 'http://summernote.org',

  newWindow: true

});

 

$('#summernote').summernote('unlink');

Callbacks

summernote支持初始化回调函数和jquery自定义事件的回调函数 在V0.7.0之后的版本中callback选项配置的位置变化了。
在V0.7.0之后的版本中callback应该被callbacks对象包裹。
在V0.6.5之后的版本中事件的回调函数键值必须使用驼峰命名法。
在V0.6.5之前的版本中基本的事件命名(比如:oninit,onenter,onfocus,onblur,onkeyup,onkeydown,onpaste)都是使用小写字符串,但是在Callbacks中的对高级特性的事件回调函数命名使用驼峰命名法,这样就造成了命名不一致,更加混乱。所以我们把所有的小写的callback改成了驼峰命名法。

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');

});

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, onBlur

// 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');

});

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

// 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');

});

onImageUpload

重写图片上传方法

// onImageUpload callback

$('#summernote').summernote({

 callbacks: {

    onImageUpload: function(files) {

      // uploadimage to server and create imgNode...

      $summernote.summernote('insertNode', imgNode);

    }

 }

});

 

// summernote.image.upload

$('#summernote').on('summernote.image.upload', function(we,files) {

 // upload image to server andcreate imgNode...

 $summernote.summernote('insertNode', imgNode);

});

onChange

// 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 ischanged.');

});

Custom button(自定义按钮)

summernote也支持自定义按钮。如果你想要创建你自己的按钮,可以定义新按钮并在options中配置它。

定义按钮

使用$.summernote.ui创建button对象,按钮具有以下属性:

  • 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 () {

      // invokeinsertText method with 'hello' on editor module.

      context.invoke('editor.insertText', 'hello');

    }

 });

 

 return button.render();  // return button as jquery object

}

将按钮作为jquery对象返回renderr()

Using button with options(在配置项中使用按钮)

在工具栏中使用button。首先,定义一个键为buttons的button对象,然后在工具栏中定义定制的按钮

$('.summernote').summernote({

 toolbar: [

    ['mybutton', ['hello']]

 ],

 

 buttons: {

    hello: HelloButton

 }

});

同样也可以在POPover中使用自定义按钮

模块化

summernote通过模块化支持功能的扩展。这种模块体系的建立受益于spring框架的启发。

关键术语

  • Module:模块
  • Context:Context包含modules和editor’s 声明的容器
  • Renderer:Renderer是用来创建元素的方法
  • UI:UI是用来新建ui元素的渲染函数

Module

Module是用来扩展功能的组件,具有生命周期,也有辅助函数和依赖于生命周期的函数

initialize

通过$(‘..’).summernote()进行初始化的时候会调用这个函数,可以用来在editor中绑定事件和创建元素

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'); // 调用editor中的bold方法
    }
  });
 
  // button.render()返回button生成的jquery对象
  this.$button = button.render();
  $toolbar.append(this.$button);
}
destroy

$(‘..’).summernote(‘destroy’)的时候调用这个方法,移除initlize即初始化时创建的元素,并解绑事件

this.destroy = function () {
  this.$button.remove();
  this.$button = null;
}
shouldInitialize

这个方法来决定模块是否会被初始化

// 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;
  }
};

配置模块

可以通过option自定义模块

$(".summernote").summernote({
  modules: {
    myModule: MyModule
  }
});

可以通过暴露的API来调用自定义模块中的方法

$(".summernote").summernote("myModule.method", 'hello');

Plugin

可以以插件形式来自定义模块

// src/mymodule.js 
$.extend($.summernote.plugins, {
  myModule: function (context) {
    // define module 
    ... 
  }
});

 

原创粉丝点击