2012-08-10 132 views
0

我正在使用HTML/Javascript設計一個簡單的富文本編輯器。它使用iframe。雖然它在IE6(以及可能更新的IE版本)中運行良好,但它在FireFox中被破壞了。 iframe無法以任何方式編輯或使用。iframe和firefox問題

的HTML <body>

<input type="button" id="bold" class="Button" value="B" onClick="fontEdit('bold');"> 
<input type="button" id="italic" class="Button" value="I" onClick="fontEdit('italic');"> 
<input type="button" id="underline" class="Button" value="U" onClick="fontEdit('underline');"> 
<hr> 
<iframe id="TextEditor" class="TextEditor"></iframe> 

的JavaScript(對於IE)

TextEditor.document.designMode="on"; 
TextEditor.document.open(); 
TextEditor.document.write('<head><style type="text/css">body{ font-family:arial; font-size:13px; }</style> </head>'); 
TextEditor.document.close(); 
TextEditor.focus(); 

上述腳本使得iframe中在IE中編輯。在FF中沒有這樣做。於是,我改變了一些事情FF版本 -

的JavaScript(對於FF)

id("TextEditor").contentWindow.designMode="on"; 
id("TextEditor").contentWindow.open(); //this line is responsible for pop-ups 
id("TextEditor").contentWindow.write('<head><style type="text/css">body{ font-family:arial; font-size:13px; }</style> </head>'); //this line throws error: id("TextEditor").contentWindow.write is not a function at the FF debug console. 
id("TextEditor").contentWindow.close(); 
id("TextEditor").focus(); 

這部分代碼,使FF挑起彈出警報空白頁面作爲目標。它仍然是壞的。現在什麼都遵循的東西一般功能,如id()fontEdit() -

function fontEdit(x,y){ 
    TextEditor.document.execCommand(x,"",y); 
    TextEditor.focus(); 
} 

function id(id){ 
    return document.getElementById(id); 
} 

function tag(tag){ 
    return document.getElementsByTagName(tag); 
} 

我敢肯定,FF不處理iframe的這種方式。那麼如何讓iframe用作富文本編輯器,而不顯示彈出窗口。請儘量避免使用jQuery,因爲我還沒有那麼好。這就是爲什麼像id()tag()這樣的自定義功能存在。

而且,我知道,還有其他免費的文本編輯器爲下載和使用,所以請不要建議我任何這樣的解決方案,不要問我爲什麼必須重新發明輪子。只有回答如果你知道我要去哪裏錯了,如果你真的可以幫助我解決了這個問題。

回答

2

由於您正在調用函數window.open而不是您請撥打document.open,因此會激發一個空白頁作爲目標的彈出式警報。

window.open:打開一個新的瀏覽器窗口。

document.open:它打開輸出流以收集任何document.write()document.writeln()方法的輸出。完成所有寫操作後,document.close()方法會顯示寫入輸出流的任何輸出。 注意:如果目標文件已經存在,它將被清除。

The open() method

這應該爲你工作:

id("TextEditor").contentWindow.document.designMode="on"; 
id("TextEditor").contentWindow.document.open(); //this line is responsible for pop-ups 
id("TextEditor").contentWindow.document.write('<head><style type="text/css">body{ font-family:arial; font-size:13px; }</style> </head>'); //this line throws error: id("TextEditor").contentWindow.write is not a function at the FF debug console. 
id("TextEditor").contentWindow.document.close(); 
+0

這完美地工作。謝謝。 – 2012-08-10 08:28:50

+1

@Samik,作爲一個額外的部分(本身不值得回答,尤其是這個答案是正確的),將id(「TextEditor」)。contentWindow.document'設置爲一個變量也會更有效率 - 相反比必須一遍又一遍地找到物體 – freefaller 2012-08-10 08:31:23

+0

@m。阿巴斯 - 當我寫上述評論時,你從答案中刪除了解釋。我建議你把它放回去(如果可能的話),因爲對於未來找到這個問題/答案的人來說,總是很好的理解**爲什麼**你的答案有效。 – freefaller 2012-08-10 08:32:39