簡體   English   中英

使用Javascript在textarea中的光標處插入文本

[英]Inserting text at cursor in a textarea, with Javascript

我已經瀏覽了網絡上的解決方案,還有一些,但它們似乎都將代碼拆分為支持IE和Firefox。 我想知道是否有更優雅的方式可以在每個瀏覽器上工作,在文本區域的光標處插入一些文本。

非常感謝,

豐富

不,沒有。 IE有TextRange對象來完成這項工作。 IE> = 9,最后一段時間的其他所有內容都在textareas和text輸入上有selectionStartselectionEnd屬性。 此特定任務也不錯:以下內容將刪除當前選擇(如果存在),在插入符號處插入文本並在插入的文本后立即重新定位插入符號,在所有主流瀏覽器中:

function insertTextAtCursor(el, text) {
    var val = el.value, endIndex, range;
    if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
        endIndex = el.selectionEnd;
        el.value = val.slice(0, el.selectionStart) + text + val.slice(endIndex);
        el.selectionStart = el.selectionEnd = endIndex + text.length;
    } else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
        el.focus();
        range = document.selection.createRange();
        range.collapse(false);
        range.text = text;
        range.select();
    }
}

實現兩者:支持FF的代碼和支持IE的代碼。 您可以使用Frameworks為兩個瀏覽器編寫代碼。 比框架將完成分割瀏覽器之間差異的工作。

這很難過,但瀏覽器不是100%兼容!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM