首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

KindEditor 編輯器自動聚焦:錨點跳轉 + focus() API 雙重保障

     編輯:程式設計綜合問答

需求場景

論壇回帖頁面:使用者點擊「回覆」按鈕,頁面滾動到底部編輯區,並自動將游標定位在 KindEditor 編輯器內,方便直接輸入。

完整實現

HTML 結構

<!-- 回覆按鈕區域 -->
<a href="#reply-editor" onclick="focusEditor()" class="reply-btn">回覆</a>

<!-- 中間可能有較長內容 -->
<div style="height: 600px;">其他樓層內容...</div>

<!-- 編輯器錨點 -->
<a name="reply-editor" id="reply-editor">&nbsp;</a>

<!-- KindEditor 容器 -->
<textarea id="editor" name="content" style="width:100%;height:300px;"></textarea>

JavaScript 初始化

var editor;
KindEditor.ready(function(K) {
    editor = K.create('#editor', {
        resizeType: 1,
        allowPreviewEmoticons: false,
        allowImageUpload: true,
        items: [
            'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
            'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
            'insertunorderedlist', '|', 'emoticons', 'image', 'link', 'fullscreen'
        ]
    });
});

// 聚焦函數:供 onclick 呼叫
function focusEditor() {
    if (editor) {
        editor.focus();  // KindEditor API:設定焦點並置游標到末尾
    }
}

關鍵點解析

技術作用
href="#reply-editor"瀏覽器原生錨點跳轉,無需 JS 即可滾動到編輯器位置
onclick="focusEditor()"點擊時觸發 JS,呼叫編輯器 API 聚焦
editor.focus()KindEditor 核心方法:聚焦 iframe 內的編輯區,並將游標移至內容末尾
name="reply-editor" / id="reply-editor"雙重保障:舊瀏覽器支援 name,HTML5 標準用 id

進階:回覆特定樓層時插入 @提及

function replyTo(floorNum, username) {
    // 1. 跳轉 + 聚焦
    location.hash = '#reply-editor';
    setTimeout(() => editor.focus(), 100); // 等待滾動完成
    
    // 2. 插入 @提及
    editor.insertHtml(`@${username} `);
    
    // 3. 游標移至末尾 (focus 已處理,雙重保險)
    var range = editor.cmd.range;
    range.collapse(false);
    range.select();
}

常見問題排查

  • ❌ editor is undefined → 確認 KindEditor.ready 回調內賦值,且全域變數 `editor` 可被 `focusEditor` 存取
  • ❌ 聚焦無效 → 檢查編輯器是否隱藏 (display:none),KindEditor 需可見才能聚焦
  • ❌ 雙重滾動 → 移除 `location.hash` 改用 `editor.focus()` 單一方式,或用 `scrollIntoView()`

其他編輯器對照

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
編輯器聚焦方法
KindEditoreditor.focus()
TinyMCEeditor.focus()
CKEditor 4editor.focus()
CKEditor 5editor.ui.focus()
WangEditoreditor.txt.focus()