簡介
Pell 是一款超輕量級的 web 文本編輯器,提供文本編輯能力,包括加粗,加斜,下劃線,列表,插入鏈接等。
Pell 可高度自定義,整個編輯器的樣式可方便地隨意調節,編輯器的所有的圖標和操作也都可以自定義。你完全可以通過簡單地修改將其變成一個屬於自己的編輯器。
Pell 的 min 版本大小只有 3.54 kB , gizp 之後只有 1.38 kB,真可謂超輕量,並且不依賴任何框架和庫。
github: https://github.com/jaredreich/pell
live demo: https://jaredreich.com/pell 試一試 pell 的驚艷表現吧。

原理和使用
實現一個編輯器可以先了解 domcument.execCommand: https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand 這個 API,Pell 使用了這個 API 對文本進行處理,因此也決定了 Pell 只支持 IE9+。

Pell 其實是實現了一個最基本的編輯器,可以說小巧夠用,也可以說簡陋。。。監聽 ActionBar 的按鈕點擊然後執行 execCommand 相應的命令罷了。
Pell 可以通過修改其樣式文件來修改編輯器的樣式,默認的 sass 也就幾行。ActionBar 上的按鈕樣式可以通過創建時自定義實現。一個小文本編輯器可以使用如下代碼自定義創建。
//執行和初始化的方法
import { exec, init } from 'pell'
const editor = init({
//綁定的 dom
element: document.getElementById('pell'),
//內容發生變化時觸發
onChange: html => {
document.getElementById('html-output').textContent = html
},
//默認以 P 標籤分隔
defaultParagraphSeparator: 'p',
styleWithCSS: true,
//自定義頂部 ActionBar
actions: [
//表示使用默認
'bold',
'underline',
//自定義
{
name: 'italic',
result: () => exec('italic')
},
//自定義 icon 等
{
name: 'custom',
icon: '<b><u><i>C</i></u></b>',
title: 'Custom Action',
result: () => console.log('YOLO')
},
{
name: 'image',
result: () => {
const url = window.prompt('Enter the image URL')
if (url) exec('insertImage', url)
}
},
{
name: 'link',
result: () => {
const url = window.prompt('Enter the link URL')
if (url) exec('createLink', url)
}
}
],
//編輯器的自定義樣式
classes: {
actionbar: 'pell-actionbar-custom-name',
button: 'pell-button-custom-name',
content: 'pell-content-custom-name',
selected: 'pell-button-selected-custom-name'
}
})
//默認文本
editor.content.innerHTML = '<b><u><i>Initial content!</i></u></b>'
Pell 實現的東西很簡單,原理也不是很難,有時候我們有想法就應該去做,即使是 demo 或許也能夠成功哦。

作者

Jared Reich 是一位來自加拿大阿爾伯塔的開發工程師
twitter:https://twitter.com/_jaredreich
