所见即所得富文本编辑器实现原理 转

如何做到编辑像文本域,又能够即时所见呢?答案就是使用iframe作为内容编辑区域。iframe本身也是一个嵌套页面,它如何能够被编辑呢?这里有一些关键的属性,它们可以做到让iframe可以被编辑。

(1). 用ifr.contentDocument || ifr.contentWindow.document方式获取iframe的文档对象
(2). 分别设置designMode属性为’on’,contentEditable属性为’true’让iframe可编辑
(3). 通过doc.body.innerHTML方法获取内容,这个内容是我们最终要插入到数据库或显示在页面上的(例如用户评论) 

 但是在实际运行的时候,你是否发现除了chrome浏览器外(用IETester, Firefox, Chrome测试)打开这个页面都处于正在加载的状态(那个轮子转啊转,转个不停…)

只要在doc.write()方法前后加上doc.open(), doc.close()就可以了(在写之前开启,写完之后关闭)。

 

最后,我们的Web程序中经常使用jQuery作为基础类库,那就把上面的代码也改造为jQuery吧。代码如下:

 

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
5 <title>KF富文本编辑器</title>
6 <script type="text/javascript" src="jquery.min.js">
7 </script>
8 <script type="text/javascript">
9 $(function(){
10 $d = $("#editor")[0].contentWindow.document; // IE、FF都兼容
11 $d.designMode="on";
12 $d.contentEditable= true;
13 $d.open();
14 $d.close();
15 $("body", $d).append("<div>A</div><div>B</div><div>C</div>");
16
17 $('#insert_img').click(function(){
18 // 在iframe中插入一张图片
19 var img = '<img src="' + $('#path').val() +'" />';
20 $("body", $d).append(img);
21 });
22
23 $('#preview').click(function(){
24 // 获取iframe的body内容,用于显示或者插入到数据库
25 alert($('#editor').contents().find('body').html());
26 $('#preview_area').html($('#editor').contents().find('body').html());
27
28 });
29 });
30
31 </script>
32
33 </head>
34
35 <body>
36
37
38 <p><iframe id="editor" width="600px" height="200px" style="border:solid 1px;"></iframe></p>
39 <input type="text" id="path" value="http://www.google.com.hk/intl/zh-CN/images/logo_cn.png"/>
40 <input type="button" id="insert_img" value="插入图片" />
41 <input type="button" id="preview" value="预览" />
42
43 <p style="border: 1px dashed #ccc;" id="preview_area"></p>
44
45 </body>
46 </html>


 

你可能感兴趣的:(编辑器)