自己动手,结合javascript和dhtml做一个ubb编辑器

看到chinaASP论坛的abc code editor了吗?是不是觉得很cool? 说真的,刚见到我还以为是用别的什么语言做的控件呢,
后来才发现没有那么神秘的。前几天做一个商品bbs,客户要求支持ubb,同时也要做一个编辑器。现在我把做ubb的思路给大家讲
一下。
首先遇到的是界面问题,实际上这个很好解决,只是利用td的onmouseover、onmouseout和onmousedown来实现,具体实现方
法件下面的代码。
其次就是实现文本效果的问题,这个可以利用textRange的execCommand方法来实现。

下面我给出一个简单的例子,你可以把它存为一个html文件,直接可以运行,这个例子的功能很简单,就是把编辑框中选定的
文字变为粗体或斜体。其他功能你可以参照这个例子自己加上。
对了,先把这两个图片存下来。

file : ubb.html

 1<html>
 2<head>
 3<title>ubb演示</title>
 4</head>
 5<body>
 6<br/><br/>
 7<table bgcolor="lightgrey" border="0" cellpadding="2" cellspacing="2" width="300">
 8<tr>
 9<td id="tdBold" onclick='doAction("Bold")' onmousedown="DoDown(tdBold );" onmouseout="On_Mouseout(tdBold);" onmouseover="On_Mouseover   
10(tdBold) ;">
11<img height="16" src="bold.gif" width="16"/>
12</td>
13<td id="tdItalic" onclick='doAction("Italic")' onmousedown="DoDown(tdItalic);" onmouseout="On_Mouseout(tdItalic);" onmouseover="On_Mouseover(tdItalic) ;">
14<img height="16" src="italic.gif" width="16"/>
15</td>
16<td width="268"> </td>
17</tr>
18<tr>
19<td colspan="3">
20<iframe border="0" height="200" id="Editor" name="Editor" scroll="no" width="300">
21</iframe>
22</td>
23</tr>
24</table>
25</body>
26</html>
 1<script language="javascript">   
 2  
 3//initialize the iframe   
 4Editor.document .designMode = "On" ;   
 5Editor.document .open ;   
 6Editor.document .write ("&nbsp;") ;   
 7Editor.document .close ;   
 8Editor.focus ();   
 9  
10function On_Mouseover(thisTD)   
11{   
12thisTD.style .borderLeft = "1px solid buttonhighlight" ;   
13thisTD.style .borderRight = "1px solid buttonshadow";   
14thisTD.style .borderTop = "1px solid buttonhighlight";   
15thisTD.style .borderBottom = "1px solid buttonshadow";   
16}   
17  
18function On_Mouseout(thisTD)   
19{   
20thisTD.style .borderLeft = "" ;   
21thisTD.style .borderRight = "";   
22thisTD.style .borderTop = "";   
23thisTD.style .borderBottom = "";   
24}   
25  
26function DoDown(thisTD)   
27{   
28thisTD.style .borderLeft = "1px solid buttonshadow";   
29thisTD.style .borderRight = "1px solid buttonhighlight";   
30thisTD.style .borderTop = "1px solid buttonshadow";   
31thisTD.style .borderBottom = "1px solid buttonhighlight";   
32thisTD.style .paddingTop = "2px";   
33thisTD.style .paddingLeft = "2px";   
34thisTD.style .paddingBottom = "0px";   
35thisTD.style .paddingRight = "0px";   
36  
37  
38}   
39  
40function doAction(str)   
41{   
42var m_objTextRange = Editor.document .selection.createRange();   
43m_objTextRange.execCommand(str) ;   
44}   
45  
46  
47</script>
Published At
Categories with Web编程
comments powered by Disqus