HTML在线编辑器原理概述

关于HTML在线编辑器的原理,普遍的观点是,原理很简单,但是真正实现起来比较复杂,因为要考虑浏览器的兼容性问题。有的网友将HTML在线编辑器的原理总结为:

         1. designMode = "on"  或   contenteditable = "true"

         2. document.execCommand()

即设置 document 的 designMode 属性为 on 或设置 contenteditable 为 true,使控件处于可编辑状态,然后通过执行 document.execCommand() 使文字加粗、倾斜、加下划线等功能。

 

HTML在线编辑器雏形实现

下面根据HTML在线编辑器的原理,实现了一个HTML在线编辑器的雏形。 

(1)通过设置 designMode 创建一个可编辑区域 

在<body>内放置一个<iframe>

<iframe id="tkeditor" style="width: 500px; height: 200px; border: 1px solid #000000;"></iframe>

iframe 是一个浮动的内嵌框架,它是我们实现在线编辑器的基本容器,但这时 iframe 是不可编辑的,我们需要js代码设置 iframe 的 designMode 属性为 on,从而实现 iframe 的可编辑模式。首先在 head 标签内添加以下 js 代码:

1 function setdesignMode()
2 {
3     //window.frames.tkeditor.document.designMode = "on";
4     //window.frames["tkeditor"].document.designMode = "on";
5     //document.getElementById("tkeditor").contentDocument.designMode = "on";
6     //document.getElementById("tkeditor").contentWindow.document.designMode = "on";
7     tkeditor.document.designMode = "on";
8     //以上几行代码在Chrome和搜狗浏览器上通过测试,均能使 iframe 设置为可编辑状态。
9 }

 然后,在<body>中添加 onload 事件:

<body onload="setdesignMode()"></body>

这样就实现了 iframe 的可编辑状态。

(2) 实现加粗、倾斜、下划线功能

在 iframe 上方添加三个按钮,设置相应的单击事件:

<input type="button" name="Bold" value="加粗" onclick="tkeditor.document.execCommand('bold',false,null)"  />
<input type="button" name="Italic" value="斜" onclick="tkeditor.document.execCommand('italic',false,null)"  />
<input type="button" name="Underline" value="下划线" onclick="tkeditor.document.execCommand('underline',false,null)"  /> 

这样,一个HTML在线编辑器的雏形就出来的,打开浏览器试一试效果。 

完整代码 下载(在Chrome和搜狗浏览器中测试通过) 

View Code 
 1 <html xmlns="http://www.w3.org/1999/xhtml">
 2 <head>
 3 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 4 <title>在线编辑器</title>
 5 <script type="text/javascript">
 6 <!--
 7 function setdesignMode()
 8 {
 9     //window.frames.tkeditor.document.designMode = "on";
10     //window.frames["tkeditor"].document.designMode = "on";
11     //document.getElementById("tkeditor").contentDocument.designMode = "on";
12     //document.getElementById("tkeditor").contentWindow.document.designMode = "on";
13     tkeditor.document.designMode = "on";
14     //以上几行代码在Chrome和搜狗浏览器上通过测试,均能使 iframe 设置为可编辑状态。
15 }
16 -->
17 </script>
18 </head>
19 
20 <body onload="setdesignMode()">
21 <input type="button" name="Bold" value="加粗" onclick="tkeditor.document.execCommand('bold',false,null)"  />
22 <input type="button" name="Italic" value="斜" onclick="tkeditor.document.execCommand('italic',false,null)"  />
23 <input type="button" name="Underline" value="下划线" onclick="tkeditor.document.execCommand('underline',false,null)"  /><br />
24 <iframe id="tkeditor" style="width: 500px; height: 200px; border: 1px solid #000000;"></iframe>
25 </body>
26 </html

 

下一步想将三个按钮的 onclick 事件分离出来,写成一个函数的形式,但是发现单纯地只在函数中写一行代码不行,希望有知道的朋友留方交流。

作者: zeyoo 发表于 2011-05-30 21:53 原文链接

推荐.NET配套的通用数据层ORM框架:CYQ.Data 通用数据层框架