編輯器中選取文字 → 點擊工具列自定義按鈕 → 在文字後插入圖示連結,連結網址帶入選取文字作為查詢參數:/map_index.html?ad=選取文字。
ckeditor/
plugins/
addmap/
plugin.js # 外掛邏輯
map.gif # 工具列圖示 (16x16 或 24x24)
(function() {
// 1. 定義按鈕點擊執行邏輯
var cmd = {
exec: function(editor) {
var selectedText = '';
var sel = editor.getSelection();
// 相容 IE 與標準瀏覽器取得選取文字
if (CKEDITOR.env.ie) {
sel.unlock(true);
selectedText = sel.getNative().createRange().text;
} else {
selectedText = sel.getNative().toString();
}
if (selectedText) {
var html = selectedText +
'<a href="/map_index.html?ad=' + encodeURIComponent(selectedText) + '">' +
'<img border="0" height="24" src="/images/map_icon.gif" width="24" />' +
'</a>';
editor.insertHtml(html);
}
}
};
// 2. 註冊外掛
var pluginName = 'addmap';
CKEDITOR.plugins.add(pluginName, {
init: function(editor) {
// 註冊命令
editor.addCommand(pluginName, cmd);
// 加入工具列按鈕
editor.ui.addButton('addmap', {
label: '插入地圖連結',
command: pluginName,
icon: this.path + 'map.gif' // 相對 plugin.js 路徑
});
}
});
})();
CKEDITOR.editorConfig = function(config) {
config.language = 'zh-cn';
config.font_names = '新細明體;微軟正黑體;Arial;Verdana;...';
config.toolbar = [
['Source', '-', 'Preview'],
['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Print', 'Link', 'Unlink', 'Anchor'],
['Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat'],
['addmap'] // ← 將自定義按鈕加入工具列
];
config.extraPlugins = 'addmap'; // ← 關鍵:載入外掛
};
| API | 用途 |
|---|---|
editor.getSelection() | 取得 Selection 物件 |
selection.getNative() | 取得原生 DOM Selection/Range |
selection.unlock(true) | IE 專用:解除選取鎖定 |
editor.insertHtml(html) | 在游標處插入 HTML 片段 |
editor.addCommand(name, cmdDef) | 註冊命令 |
editor.ui.addButton(name, btnDef) | 加入工具列按鈕 |
config.extraPlugins | 載入外部外掛 (逗號分隔多個) |
editor.addCommand(name, CKEDITOR.dialogCommand('dialogName')),彈出視窗輸入更多參數。editor.on('selectionChange', ...) 依選取內容啟用/停用按鈕。plugin.js 同層建立 lang/zh-tw.js、lang/en.js。config.extraPlugins → 外掛不載入。icon 路徑錯誤 → 按鈕顯示空白,用 this.path 取得外掛目錄絕對路徑。encodeURIComponent 選取文字 → URL 參數注入風險。unlock(true) → 取得空字串。CKEditor 5 架構全面重寫 (ES6 模組、虛擬 DOM、紅黑樹模型),外掛開發方式完全不同。維舊專案續用 CKEditor 4;新專案建議直接採用 CKEditor 5 官方套件或自訂 Plugin 類別。
掌握「選取 → 指令 → 插入 HTML」核心流程,即可快速開發各類編輯器增強功能。