用Javascript 編寫 HTML在線編輯器

用Javascript 編寫 HTML在線編輯器


在線編輯器主要有3大類:1.直接用textarea 標籤

優點:速度快,提交方便,可以用UBB標籤來彌補不能所見所得

缺點:不直觀,功能非常少

2.用 DIV或者TABLE的CONTENTEDITABLE 標籤,屬性來讓一個區域可以編輯

優點:可以很直觀,可以做各種效果

缺點:此標籤在mozilla下不可用,只適合IE瀏覽器,且對js要求高

3.用iframe或者frame的中的document的document.designMode ="On" 來實現可編輯

優點:具有上面第二條的全部優點,並且還多瀏覽器比如FF等支持

缺點:對js要求高.


以前一直不知道好多網站上所說的在線編輯器是怎麼回事,後來在文檔裏發現document 對象的一個方法。


document.execCommand(command, false, value);

才知道具體原理。


一、首先來看一個例子:

<DIV contenteditable="true" style="border:dashed blue 2px">Hello World!</DIV>


保存爲html網頁,打開看看,在DIV裏出現了一個光標,這個DIV就變成可以編輯的了。


類似的,SPAN,FONT等都可以有 contenteditable="true" 這個屬性。


再試試下面的:


<DIV contenteditable="true" style="border:dashed blue 2px">Hello World!

    <IMG src="http://p.blog.csdn.net/p_w_picpaths/p_blog_csdn_net/comstep/70786/o_logo.jpg" />

</DIV>


我們就可以拉伸圖片了。


二、具體實現:


    1、需要兩個頁面,blank.html editor.html


    2、blank.html 作爲 editor.html的一個內嵌Frame,作爲編輯框。


<html>

<body topmargin="10" leftmargin="10" bgColor="#f6f6f6">

<div id="RTC" contenteditable = true></div>

</body>

</html>


    3、editor.html 主要是一些Javascript,用來處理不同的命令。


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE> New Document </TITLE>

<META NAME="Generator" CONTENT="EditPlus">

<META NAME="Author" CONTENT="">

<META NAME="Keywords" CONTENT="">

<META NAME="Description" CONTENT="">

<SCRIPT LANGUAGE="JavaScript">

<!--

var contentHTML;

function exeCommand(command, value)

{

document.execCommand(command, false, value);

}


// 加粗

function Black()

{

var obj = frames['ifRTC'].RTC;

obj.focus();

exeCommand('Bold', '');

}


// 斜體

function Italic()

{

var obj = frames['ifRTC'].RTC;

obj.focus();

exeCommand('Italic', '');

}


// 下劃線

function UnderLine()

{

var obj = frames['ifRTC'].RTC;

obj.focus();

exeCommand('Underline', '');

}


// 向裏縮進

function Indent()

{

var obj = frames['ifRTC'].RTC;

obj.focus();

exeCommand('Indent', '');

}


// 向外縮進

function Outdent()

{

var obj = frames['ifRTC'].RTC;

obj.focus();

exeCommand('Outdent', '');

}


// 無序列表

function UnorderList()

{

var obj = frames['ifRTC'].RTC;

obj.focus();

exeCommand('InsertUnorderedList', '');

}


// 有序列表

function OrderList()

{

var obj = frames['ifRTC'].RTC;

obj.focus();

exeCommand('InsertOrderedList', '');

}


// 插入圖片

function Image()

{

var obj = frames['ifRTC'].RTC;

obj.focus();

ImagePath = window.prompt('請輸入圖片路徑:', '');

exeCommand('InsertImage', ImagePath);

}


// 預覽效果

function Preview()

{

var htmlContent = frames['ifRTC'].RTC.innerHTML;

var open = window.open('');

open.document.write(htmlContent);

}


// 查看編輯框裏的HTML源代碼

function Source()

{

var htmlContent = frames['ifRTC'].RTC.innerHTML;

if (document.all.iframeDiv.style.display == 'block')

{

    document.all.iframeDiv.style.display = 'none';

    document.all.htmlText.value = htmlContent;

    document.all.textDiv.style.display = 'block';

    document.all.htmlText.focus();

    document.all.Source.value='HTML';

}

else

{

    document.all.iframeDiv.style.display = 'block';

    document.all.textDiv.style.display = 'none';

    frames['ifRTC'].RTC.innerHTML = document.all.htmlText.value;

    frames['ifRTC'].RTC.focus();

    document.all.Source.value=' 源代碼 ';

}

}


// 增加編輯框的高度

function Add()

{

document.all.ifRTC.height = document.all.ifRTC.height*1 + 50;

}

//-->

</SCRIPT>

</HEAD>


<BODY>

<TABLE width="400"border="0">

<TR>

<TD><input type="button" value="B" name="Black"  /></TD>

<TD><input type="button" value="I" name="Italic"  /></TD>

<TD><input type="button" value="U" name="UnderLine"  /></TD>

<TD><input type="button" value="UL" name="UnorderList"  /></TD>

<TD><input type="button" value="OL" name="OrderList"  /></TD>

<TD><input type="button" value="左" name="Outdent"  /></TD>

<TD><input type="button" value="右" name="Indent"  /></TD>

<TD><input type="button" value="圖" name="Image"  /></TD>

</TR>

</TABLE>

<div id="iframeDiv" style="display:block">

<iframe id="ifRTC" width="400" height="200" border="1" src="blank.html" ></iframe>

</div>

<div id="textDiv" style="display:none">

<textarea id="htmlText" cols="50" rows="10"></textarea>

</div>

<br>

<input type="button" value=" + " name="Add"  />&nbsp;&nbsp;

<input type="button" value=" 預 覽 " name="Preview"  />&nbsp;&nbsp;

<input type="button" value=" 源代碼 " name="Source"  />

</BODY>

</HTML>


三、後記:


這裏寫的只是一個簡單的編輯器,其實重要的就是:


contenteditable="true"



document.execCommand(command, false, value);

關於 document 的一些方法,可以查看MS的文檔。

execCommand 的一些命令也可以在文檔裏找到,下面列出一些:

execCommand(command, false, value); 中的 command 可以是以下這些:


BackColorSets or retrieves the background color of the current selection.

BoldToggles the current selection between bold and nonbold.

ClearAutocompleteForFormsClears saved forms data.

CopyCopies the current selection to the clipboard.

CreateBookmarkRetrieves the name of a bookmark anchor or creates a bookmark anchor for the current selection or insertion point.

CreateLinkRetrieves the URL of a hyperlink or creates a hyperlink on the current selection.

CutCopies the current selection to the clipboard and then deletes it.

DeleteDeletes the current selection.

FontNameSets or retrieves the font for the current selection.

FontSizeSets or retrieves the font size for the current selection.

ForeColorSets or retrieves the foreground (text) color of the current selection.

FormatBlockSets or retrieves the current block format tag.

IndentIncreases the indent of the selected text by one indentation increment.

InsertButtonOverwrites a button control on the current selection.

InsertFieldsetOverwrites a box on the current selection.

InsertHorizontalRuleOverwrites a horizontal line on the current selection.

InsertIFrameOverwrites an inline frame on the current selection.

InsertImageOverwrites an p_w_picpath on the current selection.

InsertInputButtonOverwrites a button control on the current selection.

InsertInputCheckboxOverwrites a check box control on the current selection.

InsertInputFileUploadOverwrites a file upload control on the current selection.

InsertInputHiddenInserts a hidden control on the current selection.

InsertInputImageOverwrites an p_w_picpath control on the current selection.

InsertInputPasswordOverwrites a password control on the current selection.

InsertInputRadioOverwrites a radio control on the current selection.

InsertInputResetOverwrites a reset control on the current selection.

InsertInputSubmitOverwrites a submit control on the current selection.

InsertInputTextOverwrites a text control on the current selection.

InsertMarqueeOverwrites an empty marquee on the current selection.

InsertOrderedListToggles the current selection between an ordered list and a normal format block.

InsertParagraphOverwrites a line break on the current selection.

InsertSelectDropdownOverwrites a drop-down selection control on the current selection.

InsertSelectListboxOverwrites a list box selection control on the current selection.

InsertTextAreaOverwrites a multiline text input control on the current selection.

InsertUnorderedListToggles the current selection between an ordered list and a normal format block.

ItalicToggles the current selection between italic and nonitalic.

JustifyCenterCenters the format block in which the current selection is located.

JustifyLeftLeft-justifies the format block in which the current selection is located.

JustifyRightRight-justifies the format block in which the current selection is located.

OutdentDecreases by one increment the indentation of the format block in which the current selection is located.

OverWriteToggles the text-entry mode between insert and overwrite.

PasteOverwrites the contents of the clipboard on the current selection.

RefreshRefreshes the current document.

RemoveFormatRemoves the formatting tags from the current selection.

SelectAllSelects the entire document.

SaveAsSaves the current Web page to a file.

UnBookmarkRemoves any bookmark from the current selection.

UnderlineToggles the current selection between underlined and not underlined.

UnlinkRemoves any hyperlink from the current selection.

UnselectClears the current selection.












過濾html在線編輯器產生有危害代碼

2008-04-03 14:03

部分強大的在線編輯器,已經包含了代碼整理,過濾功能,但js處理的能被很輕易的饒過,服務端必須要再次過濾一次,這幾天花了點時間,寫了部分,希望對大家有點用處,本人能力有限,還請有能力的朋友補全它。


/*不需要過濾的數組*/

$htm_on=array(

"<acronym","acronym>",

"<baseFont","baseFont>",

"<button","button>",

"<caption","caption>",

"<clientInformation","clientInformation>",

"<font","font>",

"<implementation","implementation>",

"<button","button>",

"<location","location>",

"<option","option>",

"<selection","selection>",

"<strong","strong>",

"font");


$htm_on_uper=array(

"<ACRONYM","ACRONYM>",

"<BASEFONT","BASEFONT>",

"<BUTTON","BUTTON>",

"<CAPTION","CAPTION>",

"<CLIENTINFORMATION","CLIENTINFORMATION>",

"<FONT","FONT>",

"<IMPLEMENTATION","IMPLEMENTATION>",

"<BUTTON","BUTTON>",

"<LOCATION","LOCATION>",

"<OPTION","OPTION>",

"<SELECTION","SELECTION>",

"<STRONG","STRONG>",

"FONT");


/*字符格式*/

$str=strtolower($str);

$str=preg_replace("/\s+/", " ", $str);//過濾回車

$str=preg_replace("/ +/", " ", $str);//過濾多個空格


/*過濾/替換幾種形式的js*/

$str=preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si","",$str);//刪除<script>。。。</script>格式,

//$str=preg_replace("/<(script.*?)>(.*?)<(\/script.*?)>/si","&lt;\\1&gt;\\2&lt;\\3&gt;",$str);//替換爲可以顯示的,


$str=preg_replace("/<(script.*?)>/si","",$str);//刪除<script>未封閉

//$str=preg_replace("/<(script.*?)>/si","&lt;\\1&gt;",$str);//替換未封閉


/*刪除/替換表單*/

$str=preg_replace("/<(\/?form.*?)>/si","",$str);//刪除表單

//$str=preg_replace("/<(\/?form.*?)>/si","&lt;\\1&gt;",$str);//替換表單


$str=preg_replace("/<(i?frame.*?)>(.*?)<(\/i?frame.*?)>/si","",$str);//刪除框架

//$str=preg_replace("/<(i?frame.*?)>(.*?)<(\/i?frame.*?)>/si","&lt;\\1&gt;\\2&lt;\\3&gt;",$str);//替換框架


/*過濾on事件*/

$str=preg_replace("/href=(.+?)([\"|\'| |>])/ie","'href='.strtoupper('\\1').'\\2'",$str);//把href=涉及到的on轉換爲大寫。

$str=str_replace($htm_on,$htm_on_uper,$str);//把<font,font>換爲大寫,dhtml標籤字符,正則判斷太煩瑣,採用轉換辦法。

$str=preg_replace("/(on[^ \.<>]+?)([ |>])/s","\\2",$str);//取掉on事件


/*過濾超級連接的js*/

$str=preg_replace("/(href|src|background|url|dynsrc|expression|codebase)[=:\(]([ \"\']*?\w+\..*?|javascript|vbscript:[^>]*?)(\)?)([ >\/])/si","\\1='#' \\3\\4",$str);//取掉href=javascript:


//返回小寫字符

$str=strtolower($str);

$str=str_replace("&","&#x26;",$str);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章