背景:
CREAT需要進行文本分析,主要的任務就是從一大段原始需求文本中,通過人工或者自動的手段,識別出有用的元素,並打上標記。
由於自然文本的任意性,用自動的方法無法完全精確地得出文本的處理結果,即使是人工處理,也往往需要進行幾輪迭代式的分析處理。
Web編輯器即使設計來支援人工處理的這一過程的。
實現說明:
IFrame作為編輯器主體。
設定一下iframe的屬性,iframe即可作為編輯器了。
<iframe frameborder="0" id="WebEditor" style="border: 1px dashed black;
height: 320px; width: 760px"></iframe>
<script language="javascript">
Editor = document.getElementById("WebEditor").contentWindow;
Editor.document.designMode = "on";//使document處於可編輯狀態
Editor.document.open();//For FF, 開啟新的document以便編輯新內容
//Editor.document.write("");//可以設定header資訊等, Iframe可以看成一個獨立的html頁面
Editor.document.close();//關閉document,強制發送資料顯示
</script>
Javascript處理文字格式設定
調用execCommand函數處理文本,可以實現粗斜下劃、對齊、超連結、字型(大小、顏色等功能)
execCommand函數的文法:
bSuccess = object . execCommand ( sCommand , bUserInterface , vValue )
document.execCommand() 解析
function format(what, opt)
{
Editor.focus();
Editor.document.execCommand(what, false, opt);
}
識別選擇的文本,操縱DOM
這裡有幾個FF和IE不同的地方,一個是斷行符號,IE下是<p>,比FF的<br/>空了很多,解決方案是重載編輯器document的斷行符號事件:
Editor.document.onkeypress = fnKeypress;
function fnKeypress(){
if(document.all){
var ev = Editor.event;
if(ev.keyCode==13 && !ev.shiftKey){//判斷斷行符號鍵
var s = Editor.document.selection;
if (s!=null){
var r = s.createRange();
if (r!=null) {
r.pasteHTML("<BR/>");
r.select();//將游標移動到新行
}
}
return false;
}
}
}
處理選擇的文本:
function message()
{
if(document.all)//如果是 IE. (雖然,FF也可以用document.all)
alert(Editor.document.selection.createRange().text);
else{
//alert(Editor.document.getSelection());
alert(Editor.getSelection());
var selection = Editor.getSelection().getRangeAt(0);
var linkElement = Editor.document.createElement("a"); //建立一個新的<A>節點
linkElement.href = "http://asers.blog.sohu.com";//設定<A>節點的href屬性
selection.surroundContents(linkElement);//加入超連結
}
}
插入html代碼:
function insert(html)
{
debugger;
if(window.event)
Editor.document.selection.createRange().pasteHTML(html);
else
format("insertHTML", html);
}
Demo:
web編輯器demo
參考:
IE和Firefox 對於相同的原始碼解析有所有不同
JS的IE和FF相容性問題的匯總小結
Gecko DOM Reference