这个jQuery Bootstrap小插件(5KB, < 200 行代码)可以将任何一个DIV转变成一个WYSIWYG富文本编辑器,灵感来自于 CLEditor 和 bootstrap-wysihtml5. 下面是他的主要特色:
While building a content editor for MindMup we found plenty of good HTML5 WYSWYG editors online, but most were duplicating functionality that already exists in JQuery and Bootstrap, implementing things that were meanwhile added to HTML5 and supported in major browsers, or doing too much magic such as inserting IFrames with backup text-areas. Most of this was to work around quirks in older browsers (which we didn't need) and caused focus problems on touch devices (which was an issue for us). Too much magic caused problems with bootstrap modals (a must for us). Most editors also build their own toolbars, which embed additional CSS and images and always turn out to be much worse than standard Bootstrap buttons.
It turns out, with HTML5, everything we need can fit into less than 5K. We built this tiny tiny editor that does everything we need, does not impose any particular additional CSS and uses modern browser functionality without reimplementing JQuery and Bootstrap.
It's released under the MIT license, so fork and enjoy!
$('#editor').wysiwyg();
不要忘了给容纳编辑器的div设置样式:
#editor {overflow:scroll; max-height:300px}
如果你希望在移动设备浏览器上使用此编辑器,一定要看看 如何设置样式才能针对移动设备屏幕做优化并提升用户体验(很不幸,本页面中的编辑器并没有针对移动设备做优化)。
你还可以为编辑器创建一个工具条(请在本页面点鼠标右键查看源码,本页面就是一个很好的案例):
<div class="btn-toolbar" data-role="editor-toolbar" data-target="#editor"> ... </div>
通过在工具条上添加一个带有data-edit属性的链接(a标签),可以让其执行简单的命令。
<a data-edit="bold">...</a>
为了执行更复杂的命令,可以为data-edit再添加一个参数;或者将链接用输入框(input标签)替代,并给输入框设置相应的data-edit命令(输入框中的数据将作为命令参数)。对于文件输入框,文件的内容将使用FileReader API来读取,读取到的数据作为命令执行结果。
<a data-edit="fontName Arial">...</a> ... <input type="text" data-edit="createLink"/> ... <input type="file" data-edit="insertImage" />
用标准的jQuery方法就可以设置、获取编辑器的内容或者为其设置焦点。此外,还可以获取清除HTML标签后的内容:
$('#editor').cleanHtml()
Bootstray-WYSIWYG由Bootstrap中文网翻译整理