top
Loading...
自己動手,結合javascript和dhtml做一個ubb編輯器(附例子代碼)
看到chinaASP論壇的abc code editor了嗎?是不是覺得很cool? 說真的,剛見到我還以為是用別的什么語言做的控件呢,后來才發現沒有那么神秘的。前幾天做一個商品bbs,客戶要求支持ubb,同時也要做一個編輯器。現在我把做ubb的思路給大家講一下。
首先遇到的是界面問題,實際上這個很好解決,只是利用td的onmouseover、onmouseout和onmousedown來實現,具體實現方法件下面的代碼。
其次就是實現文本效果的問題,這個可以利用textRange的execCommand方法來實現。

下面我給出一個簡單的例子,你可以把它存為一個html文件,直接可以運行,這個例子的功能很簡單,就是把編輯框中選定的文字變為粗體或斜體。其他功能你可以參照這個例子自己加上。
對了,先把這兩個圖片存下來。

file : ubb.html

<HTML>
<HEAD>

<TITLE>ubb演示</TITLE>
</HEAD>
<BODY>
<br><br>
<table width=300 cellspacing=2 cellpadding=2 border=0 bgcolor=lightgrey>
<tr>
<td id=tdBold onclick=doAction("Bold") onmousedown="DoDown(tdBold );" onmouseover = "On_Mouseover(tdBold) ;" onmouseout="On_Mouseout(tdBold);">
<img src='bold.gif' width=16 height=16 >
</td>
<td id=tdItalic onclick=doAction("Italic") onmousedown="DoDown(tdItalic);" onmouseover = "On_Mouseover(tdItalic) ;" onmouseout="On_Mouseout(tdItalic);">
<img src='italic.gif' width=16 height=16 >
</td>
<td width=268> </td>
</tr>
<tr>
<td colspan=3>
<iframe id=Editor name=Editor border=0 scroll=no width=300 height=200>
</iframe>
</td>
</tr>
</table>

</BODY>
</HTML>

<script language=javascript>

//initialize the iframe
Editor.document .designMode = "On" ;
Editor.document .open ;
Editor.document .write (" ") ;
Editor.document .close ;
Editor.focus ();

function On_Mouseover(thisTD)
{
thisTD.style .borderLeft = "1px solid buttonhighlight" ;
thisTD.style .borderRight = "1px solid buttonshadow";
thisTD.style .borderTop = "1px solid buttonhighlight";
thisTD.style .borderBottom = "1px solid buttonshadow";
}

function On_Mouseout(thisTD)
{
thisTD.style .borderLeft = "" ;
thisTD.style .borderRight = "";
thisTD.style .borderTop = "";
thisTD.style .borderBottom = "";
}

function DoDown(thisTD)
{
thisTD.style .borderLeft = "1px solid buttonshadow";
thisTD.style .borderRight = "1px solid buttonhighlight";
thisTD.style .borderTop = "1px solid buttonshadow";
thisTD.style .borderBottom = "1px solid buttonhighlight";
thisTD.style .paddingTop = "2px";
thisTD.style .paddingLeft = "2px";
thisTD.style .paddingBottom = "0px";
thisTD.style .paddingRight = "0px";


}

function doAction(str)
{
var m_objTextRange = Editor.document .selection.createRange();
m_objTextRange.execCommand(str) ;
}

</script>


北斗有巢氏 有巢氏北斗