DIV CSS 佈局教程網

在 textarea 游標位置插入文字或表情
編輯:JavaScript綜合知識     

聊天室、留言板的表情面板,需要把選中的表情插入到「使用者目前打字的位置」,而不是永遠附加在最後。要做到這件事,關鍵是讀取 textarea 的 selectionStart/selectionEnd。

外掛定義

(function ($) {
  $.fn.extend({
    insertAtCaret: function (myValue) {
      var $t = $(this)[0];

      // 分支一:IE 舊版的 document.selection
      if (document.selection) {
        this.focus();
        var sel = document.selection.createRange();
        sel.text = myValue;
        this.focus();
      }
      // 分支二:標準的 selectionStart / selectionEnd
      else if ($t.selectionStart || $t.selectionStart == '0') {
        var startPos = $t.selectionStart;
        var endPos = $t.selectionEnd;
        var scrollTop = $t.scrollTop;

        $t.value = $t.value.substring(0, startPos) + myValue +
                   $t.value.substring(endPos, $t.value.length);

        this.focus();
        // 插入後把游標移到插入內容之後
        $t.selectionStart = startPos + myValue.length;
        $t.selectionEnd = startPos + myValue.length;
        $t.scrollTop = scrollTop;
      }
      // 分支三:完全拿不到位置資訊,只能附加到尾端
      else {
        this.value += myValue;
        this.focus();
      }
    }
  });
})(jQuery);

三個分支的意義

標準分支:selectionStart / selectionEnd

這兩個屬性給出選取範圍的起訖位置。插入的作法是字串拼接:把「游標前」+「要插入的內容」+「游標後(從 endPos 起)」重組。注意這裡用的是 endPos 而非 startPos,因此若使用者有選取一段文字,插入時會把它替換掉——這與多數編輯器的行為一致。

scrollTop 的保存

改寫 value 會讓 textarea 的捲動位置跳回頂端。先把 scrollTop 存起來、插入後再設回去,使用者才不會突然被丟到最前面。這是很多實作會漏掉的細節。

游標位置的前移

插入後必須把 selectionStart 與 selectionEnd 設成 startPos + myValue.length,游標才會停在插入內容之後,可以繼續打字。少了這步,游標會停在插入內容之前,體感很差。

呼叫方式

$("#textareaId").insertAtCaret("新表情");

現代化建議

document.selection 是 IE 專屬寫法,現在可以直接移除第一個分支。另外有兩點值得改用標準 API:

$.fn.insertAtCaret = function (text) {
  return this.each(function () {
    if (typeof this.setRangeText === 'function') {
      // 標準做法:一行完成插入與游標定位
      this.setRangeText(text, this.selectionStart, this.selectionEnd, 'end');
    } else {
      var s = this.selectionStart, e = this.selectionEnd;
      this.value = this.value.slice(0, s) + text + this.value.slice(e);
      this.selectionStart = this.selectionEnd = s + text.length;
    }
    this.focus();
  });
};

setRangeText 支援 mode 參數,'end' 會自動把游標移到插入內容之後,省去手動計算。此外,若插入表情後需要觸發 React 或 Vue 的資料綁定,單純改 value 不會被偵測到,需搭配 dispatchEvent(new Event('input', { bubbles: true })) 通知框架更新狀態。

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