DIV CSS 佈局教程網

在可編輯 div 中於光標位置插入內容的方法
編輯:JavaScript綜合知識     

製作即時訊息輸入框時,常需要在使用者的游標位置插入表情或文字。這篇文章示範如何啟用 div 編輯模式、取得游標位置,並在該處插入 HTML 內容。

啟用編輯模式

只要加上 contenteditable=true,div 就能像輸入框一樣打字:

<div contenteditable=true id="divTest"></div>

取得與移動游標位置(IE 舊寫法)

var cursor = 0; // 光標位置
document.onselectionchange = function () {
    var range = document.selection.createRange();
    var srcele = range.parentElement();
    var copy = document.body.createTextRange();
    copy.moveToElementText(srcele);
    for (cursor = 0; copy.compareEndPoints("StartToStart", range) < 0; cursor++) {
        copy.moveStart("character", 1); // 逐步記錄 cursor 的數量
    }
};

現代瀏覽器:insertHtmlAtCaret

這是跨瀏覽器相容性較好的做法,透過 Selection 與 Range API 在游標處插入節點,插入後還會保留選取狀態:

function insertHtmlAtCaret(html) {
    var sel, range;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ((node = el.firstChild)) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        document.selection.createRange().pasteHTML(html);
    }
}

搭配按鈕使用

<button type="button" onclick="document.getElementById('test').focus(); insertHtmlAtCaret('<b>INSERTED</b>');">插入字符</button>
<div contentEditable="true" style="height:50px; border:2px solid red;" id="test"> </div>

核心概念是:先取得目前的 Selection 與 Range,刪除任何選取內容,再把要插入的 HTML 轉成文件片段(DocumentFragment)塞進游標位置,最後重新設定選取範圍,讓游標停在插入內容之後。若搭配 jQuery,也能用類似邏輯實作表情選擇器之類的互動。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved