CKEditor 4 作為經典富文本編輯器,預設配置往往無法滿足 CMS 系統的深度業務需求。本文針對 PHPCMS V9 內置 CKEditor 場景,詳解四大高頻定制:批量移除超鏈接、圖片上傳自動填充 Alt、Enter 鍵行為切換、集成「一鍵排版」外掛,提供具體文件路徑、代碼修改點與驗證步驟。
statics/js/ckeditor/statics/js/ckeditor/config.jsphpcms/libs/classes/form.class.php文件:statics/js/ckeditor/ckeditor.js(壓縮版,建議操作源碼 ckeditor_src.js 再壓縮)
搜尋:execCommand('unlink'
修改前:
$.execCommand('unlink',false,null);
修改後:
$.execCommand('unlink',false,true); // 第三參數 true = 移除所有匹配鏈接
原理:CKEditor unlink 命令第三參數 true 表示「移除選區內所有鏈接」,false/null 僅移除光標所在鏈接。
文件:statics/js/ckeditor/plugins/image/dialogs/image.js
搜尋:accessKey:'T','default':''(Alt 輸入框定義)
修改後:
accessKey:'T','default':$('#title').val() // 假設對話框標題輸入框 id="title"
注意:此處需確保對話框 DOM 已就緒,建議在 onShow 事件中動態賦值:
onShow: function() {
var titleInput = this.getContentElement('info', 'txtAlt');
var titleVal = this.getContentElement('info', 'txtUrl').getValue(); // 或其他邏輯
titleInput.setValue(titleVal);
}
文件:statics/js/ckeditor/config.js
預設行為:
<br>(換行)<p>(新段落)修改為 Word 習慣:
config.enterMode = CKEDITOR.ENTER_P; // Enter 產生 <p>
config.shiftEnterMode = CKEDITOR.ENTER_BR; // Shift+Enter 產生 <br>
常量對照:
| 常量 | 行為 |
|---|---|
CKEDITOR.ENTER_P | 新段落 <p> |
CKEDITOR.ENTER_BR | 換行 <br> |
CKEDITOR.ENTER_DIV | 新塊 <div> |
步驟 1:註冊工具欄按鈕
文件:phpcms/libs/classes/form.class.php
搜尋:['Maximize'](工具欄按鈕陣列)
修改:在其下方添加 'autoformat':
$toolbar = [
// ... 現有按鈕 ...
['Maximize'],
['autoformat'], // 新增
];
步驟 2:載入外掛
文件:statics/js/ckeditor/config.js
搜尋:config.extraPlugins
修改:
config.extraPlugins = 'capture,autoformat'; // 原有 capture,追加 autoformat
步驟 3:放置外掛文件
將 autoformat 外掛目錄放入 statics/js/ckeditor/plugins/autoformat/,結構:
plugins/autoformat/
├── plugin.js // 核心邏輯
├── icons/autoformat.png
└── dialogs/autoformat.js (可選)
plugin.js 核心邏輯示例(執行 HTML 清理、段落合併、樣式統一):
CKEDITOR.plugins.add('autoformat', {
icons: 'autoformat',
init: function(editor) {
editor.addCommand('autoformat', {
exec: function(editor) {
var html = editor.getData();
// 1. 移除空段落
html = html.replace(/<p>\s*<\/p>/gi, '');
// 2. 統一字體大小/顏色(移除內聯 style)
html = html.replace(/style\s*=\s*["'][^"']*["']/gi, '');
// 3. 合併相鄰同樣式段落(簡易版)
// ...
editor.setData(html);
editor.fire('saveSnapshot');
}
});
editor.ui.addButton('Autoformat', {
label: '一鍵排版',
command: 'autoformat',
toolbar: 'cleanup,10'
});
}
});
config.js 版本號 config.timestamp = '20240101';<p>,Shift+Enter → <br>| 現象 | 原因 | 解決 |
|---|---|---|
| 工具欄無新按鈕 | form.class.php 修改未生效/緩存未清 | 更新後台緩存、檢查按鈕名稱拼寫 |
報錯 autoformat is not defined | plugin.js 未載入/路徑錯誤 | 檢查 plugins/autoformat/plugin.js 存在、extraPlugins 拼寫 |
| Alt 不自動填充 | jQuery 未載入/選取器錯誤 | 改用原生 document.getElementById 或在 onShow 事件賦值 |
| Enter 行為不變 | config.js 被瀏覽器緩存 | 加 timestamp 參數或清除緩存 |
CKEditor 4 定制核心在於「修改核心命令參數 → 調整 config 入口 → 註冊工具欄按鈕 → 載入外掛」四步走。本文四大定制覆蓋了內容清理、無障礙合規、編輯習慣適配、排版效率提升四大維度,代碼修改量極小(<50 行),卻能顯著提升編輯體驗與內容質量。建議將修改納入版本控制,並編寫自動化測試驗證核心行為,防止升級 CKEditor 版本時失效。