FCKeditor 曾是 CMS 與後台系統的標準所見即所得編輯器。它透過 FCKeditorAPI 這個全域物件把內部能力開放給 JavaScript 使用。以下是五個最常用的操作。
// 1. 取得編輯器中的內容(XHTML 格式)
function getEditorContents(){
var oEditor = FCKeditorAPI.GetInstance("content");
alert(oEditor.GetXHTML(true));
}
// 2. 向編輯器插入指定的 HTML
function insertHTMLToEditor(codeStr){
var oEditor = FCKeditorAPI.GetInstance("content");
if (oEditor.EditMode == FCK_EDITMODE_WYSIWYG){
oEditor.InsertHtml(codeStr);
} else {
return false;
}
}
// 3. 統計編輯器內容的字數
function getLength(){
var oEditor = FCKeditorAPI.GetInstance("content");
var oDOM = oEditor.EditorDocument;
var iLength;
if (document.all){
iLength = oDOM.body.innerText.length;
} else {
var r = oDOM.createRange();
r.selectNodeContents(oDOM.body);
iLength = r.toString().length;
}
alert(iLength);
}
// 4. 執行指定的編輯指令
function ExecuteCommand(commandName){
var oEditor = FCKeditorAPI.GetInstance("content");
oEditor.Commands.GetCommand(commandName).Execute();
}
// 5. 設定編輯器的內容
function SetContents(codeStr){
var oEditor = FCKeditorAPI.GetInstance("content");
oEditor.SetHTML(codeStr);
}
GetInstance(id) 是所有操作的入口,參數是 FCKeditor 實例的名稱(此處為 "content")。取得 oEditor 物件後,各項能力都是它的方法或屬性。
GetXHTML(true) 取得格式化後的 XHTML 原始碼,參數控制是否做美化縮排。若只要純文字,可用 oEditor.EditorDocument.body.innerText。
InsertHtml() 在游標目前位置插入 HTML。它只在所見即所得模式(WYSIWYG)下有效,原始碼模式下 EditMode 是 FCK_EDITMODE_SOURCE,此時插入邏輯完全不同,所以原範例先判斷模式是正確的做法。
SetHTML() 則是整份取代編輯器內容,不分模式都能用。
Commands.GetCommand(name).Execute() 用來觸發工具列上的指令,例如 'Bold'、'Link'、'JustifyLeft',等同使用者點擊工具列按鈕。
那段 if (document.all) 的判斷是為了相容 IE 與其他瀏覽器:IE 用 innerText 直接取可見文字;其他瀏覽器則用 Range API 選取 body 全部內容再轉字串。
今天可以直接用標準寫法:
function getLength(){
var oEditor = FCKeditorAPI.GetInstance("content");
var text = oEditor.EditorDocument.body.textContent || '';
// 去掉多餘空白後計算
return text.replace(/\s+/g, '').length;
}
document.all 這種偵測方式早已不合時宜——它是「偵測物件的存在」而非「偵測功能」,而且 document.all 幾乎所有瀏覽器都基於相容理由實作了,這個判斷幾乎永遠為真。正確的做法是功能偵測:
if (typeof body.textContent === 'string'){
// 用 textContent
} else if (typeof body.innerText === 'string'){
// 退回到 innerText
}
onComplete 或 instanceReady 事件後才操作,否則 GetInstance 會回傳 undefined。FCKeditorAPI.GetInstance('content').UpdateLinkedField() 把編輯器內容寫回後方的 textarea,否則伺服器收到的是空值。這是最常見的「明明有打字卻存不進資料庫」的原因。FCKeditor 已停止維護,後繼的 CKEditor 4 / 5 與 TinyMCE 是常見選擇。它們的 API 設計更清楚,例如 CKEditor 5:
// 取得資料
var data = editor.getData();
// 設定資料
editor.setData('<p>新內容</p>');
// 監聽變化
editor.model.document.on('change:data', () => {
console.log(editor.getData());
});
若內容以純文字為主、不需要複雜排版,用 <textarea> 搭配 Markdown 編輯器往往比富文本編輯器更好維護,資料格式也更穩定、更容易做版本差異比對。