效果图如下:
思路:
首先选择用iframe来承载这个富文本编辑器,因为iframe有一个属性contentEditable,让内容可编辑。然后它的execCommand方法又可以实现多种效果。最早出现这些方法和属性的是IE浏览器,后来其他浏览器也纷纷支持了。
现在的富文本编辑器的适用范围越来越广,但我看到的网上的插件啊资源啊基本只有百度一家有,而且很多网站也直接用了百度的插件。
但是如果我们要自己做一个简易的呢?
直接使用百度的插件肯定是太繁重了,尤其是手机端,肯定不适用。
接下来就看看该如何实现呢?
首先推荐一本书叫《javascript高级程序设计》,里面专门有讲富文本编辑器的制作。另外找了一篇别人的博客,里面对execCommand有详细的介绍,可以作为参考查阅用:javascript中的execCommand解析。
html代码:
<iframe class="add-activity-detail" id="editor" ></iframe>
<div class="text-edit-container">
<ul class="text-edit">
<li><strong>B</strong></li>
<li><i>I</i></li>
<li><u>u</u></li>
<li><s>abc</s></li></ul></div>
js代码:
//内容编辑
$(function() {
$d = $("#editor")[0].contentWindow.document; // IE、FF都兼容
$d.designMode = "on";
$d.contentEditable = true;
$d.open();
$d.close();
win=document.getElementById("editor").contentWindow;
//win.document.execCommand("Bold",false,null);
//win.document.execCommand('Italic');
//document.execCommand('Underline');
win.focus();
$(".text-edit li strong").on("click",function(e){
win.document.execCommand("Bold",false,null);
e.stopPropagation;
})
$(".text-edit li i").on("click",function(e){
win.document.execCommand('Italic');
e.stopPropagation;
})
$(".text-edit li u").on("click",function(e){
win.document.execCommand('Underline');
e.stopPropagation;
})
$(".text-edit li s").on("click",function(e){
win.document.execCommand('StrikeThrough');
e.stopPropagation;
})
})
从代码中可以看出,要使用的话只要先让内容可编辑,然后打开,关闭,就可以使用了。
$d = $("#editor")[0].contentWindow.document; // IE、FF都兼容
$d.designMode = "on";
$d.contentEditable = true;
$d.open();
$d.close();
然后就是用execCommand实现各种功能。
疑问及解决方法
iframe本来是不可以编辑的,因此它的光标是模拟出来的而不是真实存在的。所以在移动端就会出现这样的情况,用户以为已经聚焦了,为什么不能输入呢?
解决这个问题可以采取事件触发,比如在其他元素上点击可以触发富文本编辑器的focus(),那就可以直接输入了。
如何获取这个富文本编辑器的内容呢?
直接document.getElementById(“#editor”).html()就可以了。
总结
其实富文本编辑器在移动端的使用体验并不是非常好,如果不是非常有必要的话,还是不采用的好。