1. 程式人生 > >summernote富文字編輯器的基本使用

summernote富文字編輯器的基本使用

基礎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
    ... 

  }

});