(function () {
// https://developer.mozilla.org/zh-CN/docs/Web/API/Document/execCommand
var commands = [
{ cmd: 'bold', text: '加粗' },
{ cmd: 'italic', text: '斜体' },
{ cmd: 'decreaseFontSize', text: '小号' },
{ cmd: 'increaseFontSize', text: '大号' },
{ cmd: 'underline', text: '下划线' },
{ cmd: 'strikeThrough', text: '删除线' },
{ cmd: 'insertOrderedList', text: '有序列表' },
{ cmd: 'insertUnorderedList', text: '无序列表' },
{ cmd: 'createLink', text: '链接', input: '请输入一个链接' },
{ cmd: 'insertImage', text: '插图', input: '请输入一个图片地址' },
{ cmd: 'justifyCenter', text: '居中' },
{ cmd: 'justifyLeft', text: '左对齐' },
{ cmd: 'justifyRight', text: '右对齐' },
{ cmd: 'formatBlock', text: 'H1', arg: 'H1' },
{ cmd: 'formatBlock', text: 'H2', arg: 'H2' },
{ cmd: 'formatBlock', text: 'H3', arg: 'H3' },
{ cmd: 'formatBlock', text: 'H4', arg: 'H4' },
{ cmd: 'formatBlock', text: 'H5', arg: 'H5' },
{ cmd: 'formatBlock', text: 'H6', arg: 'H6' },
{ cmd: 'formatBlock', text: '引用', arg: 'BLOCKQUOTE' },
{ cmd: 'formatBlock', text: 'PRE', arg: 'PRE' },
{ cmd: 'insertHorizontalRule', text: 'HR' }
]
var $tools = document.querySelector('.editor-tools')
var $content = document.querySelector('.editor-content')
$tools.innerHTML = commands.map(function (item) {
return document.queryCommandSupported(item.cmd) ?
'<button type="button" class="btn btn-default" data-cmd="' + item.cmd + '"' +
(item.arg ? ' data-arg="' + item.arg + '"' : '') +
(item.input ? 'data-input="' + item.input + '"' : '') +
'>' + item.text + '</button>' : ''
}).join('')
$tools.addEventListener('click', function (e) {
var $this = e.target
if ($this.tagName !== 'BUTTON') {
return
}
var data = $this.dataset
var arg = data.arg || (data.input && window.prompt(data.input))
document.execCommand(data.cmd, true, arg)
})
})()