DIV CSS 佈局教程網

取得輸入框游標的頁面座標:跨瀏覽器相容的完整實作
編輯:JavaScript綜合知識     

想在輸入框游標旁邊跳出一個提示氣泡、自動完成清單,或插入表情圖示,你就會需要「游標目前在第幾行第幾列」換算成「頁面座標」。這件事在瀏覽器之間差異極大,IE 有 document.selection 可以用,標準瀏覽器則得靠一個巧妙的替代技巧。

核心思路

標準瀏覽器沒有直接取得游標座標的 API。做法是:建立一個和輸入框樣式完全相同的隱藏 div,把游標前面的文字複製進去,在文字尾端插入一個寬度為 0 的 span 當「游標替身」,再量這個 span 的位置——它就是游標的位置。這就是整套程式最需要理解的部分。

完整程式碼

var kingwolfofsky = {

  /**
   * 取得輸入游標在頁面中的座標
   * @param {HTMLElement} 輸入框元素
   * @return {Object} 回傳 left、top、bottom
   */
  getInputPositon: function (elem) {
    if (document.selection) {          // IE 走這條路
      elem.focus();
      var Sel = document.selection.createRange();
      return {
        left:   Sel.boundingLeft,
        top:    Sel.boundingTop,
        bottom: Sel.boundingTop + Sel.boundingHeight
      };
    } else {
      var that = this;
      var cloneDiv = '{$clone_div}', cloneLeft = '{$cloneLeft}',
          cloneFocus = '{$cloneFocus}';
      var none = '<span style="white-space:pre-wrap;"> </span>';
      var div   = elem[cloneDiv]   || document.createElement('div');
      var focus = elem[cloneFocus] || document.createElement('span');
      var text  = elem[cloneLeft]  || document.createElement('span');
      var offset = that._offset(elem),
          index  = this._getFocus(elem),
          focusOffset = { left: 0, top: 0 };

      if (!elem[cloneDiv]) {
        elem[cloneDiv] = div; elem[cloneFocus] = focus; elem[cloneLeft] = text;
        div.appendChild(text);
        div.appendChild(focus);
        document.body.appendChild(div);
        focus.innerHTML = '|';
        focus.style.cssText = 'display:inline-block;width:0px;overflow:hidden;'
                            + 'z-index:-100;word-wrap:break-word;word-break:break-all;';
        div.className = this._cloneStyle(elem);     // 複製輸入框的樣式
        div.style.cssText = 'visibility:hidden;display:inline-block;position:absolute;'
                          + 'z-index:-100;word-wrap:break-word;word-break:break-all;'
                          + 'overflow:hidden;';
      }

      div.style.left = this._offset(elem).left + "px";
      div.style.top  = this._offset(elem).top  + "px";

      // 把游標前的文字放進替身 div,換行與空白要特別處理
      var strTmp = elem.value.substring(0, index)
        .replace(/</g, '&lt;').replace(/>/g, '&gt;')
        .replace(/\n/g, '<br/>').replace(/\s/g, none);
      text.innerHTML = strTmp;

      focus.style.display = 'inline-block';
      try { focusOffset = this._offset(focus); } catch (e) { }
      focus.style.display = 'none';

      return {
        left:   focusOffset.left,
        top:    focusOffset.top,
        bottom: focusOffset.bottom
      };
    }
  },

  // 複製元素樣式並回傳產生的 class 名稱
  _cloneStyle: function (elem, cache) {
    if (!cache && elem['${cloneName}']) return elem['${cloneName}'];
    var className, name, rstyle = /^(number|string)$/;
    var rname = /^(content|outline|outlineWidth)$/;  // Opera: content;IE8: outline
    var cssText = [], sStyle = elem.style;
    for (name in sStyle) {
      if (!rname.test(name)) {
        var val = this._getStyle(elem, name);
        if (val !== '' && rstyle.test(typeof val)) {
          name = name.replace(/([A-Z])/g, "-$1").toLowerCase();
          cssText.push(name); cssText.push(':');
          cssText.push(val);  cssText.push(';');
        }
      }
    }
    cssText = cssText.join('');
    elem['${cloneName}'] = className = 'clone' + (new Date).getTime();
    this._addHeadStyle('.' + className + '{' + cssText + '}');
    return className;
  },

  // 向頁首插入樣式
  _addHeadStyle: function (content) {
    var style = this._style[document];
    if (!style) {
      style = this._style[document] = document.createElement('style');
      document.getElementsByTagName('head')[0].appendChild(style);
    }
    style.styleSheet && (style.styleSheet.cssText += content)
      || style.appendChild(document.createTextNode(content));
  },
  _style: {},

  // 取得最終樣式
  _getStyle: 'getComputedStyle' in window
    ? function (elem, name) { return getComputedStyle(elem, null)[name]; }
    : function (elem, name) { return elem.currentStyle[name]; },

  // 取得游標在文字方塊中的位置(字元索引)
  _getFocus: function (elem) {
    var index = 0;
    if (document.selection) {                 // IE
      elem.focus();
      var Sel = document.selection.createRange();
      if (elem.nodeName === 'TEXTAREA') {
        var Sel2 = Sel.duplicate();
        Sel2.moveToElementText(elem);
        index = -1;
        while (Sel2.inRange(Sel)) {
          Sel2.moveStart('character');
          index++;
        }
      } else if (elem.nodeName === 'INPUT') {
        Sel.moveStart('character', -elem.value.length);
        index = Sel.text.length;
      }
    } else if (elem.selectionStart || elem.selectionStart == '0') {
      index = elem.selectionStart;            // Firefox 等支援 selectionStart
    }
    return index;
  },

  // 取得元素在頁面中的位置
  _offset: function (elem) {
    var box = elem.getBoundingClientRect(),
        doc = elem.ownerDocument,
        body = doc.body,
        docElem = doc.documentElement;
    var clientTop  = docElem.clientTop  || body.clientTop  || 0;
    var clientLeft = docElem.clientLeft || body.clientLeft || 0;
    var top  = box.top  + (self.pageYOffset || docElem.scrollTop)  - clientTop;
    var left = box.left + (self.pageXOffset || docElem.scrollLeft) - clientLeft;
    return {
      left: left, top: top,
      right: left + box.width, bottom: top + box.height
    };
  }
};

// 呼叫範例:把 #show 定位到游標下方
function getPosition(ctrl) {
  var p = kingwolfofsky.getInputPositon(ctrl);
  document.getElementById('show').style.left = p.left + "px";
  document.getElementById('show').style.top  = p.bottom + "px";
}

各個私有方法在忙什麼

  • _getFocus:算出游標前面有幾個字。IE 用 TextRange 一格一格數,標準瀏覽器直接讀 selectionStart。
  • _cloneStyle:把輸入框的 computed style 全部抄一份,產生一個 class 塞進 head。少了這步,替身 div 的字型、字距和真正的輸入框不同,量出來的座標就會偏。
  • _offset:用 getBoundingClientRect 加上捲動量,換算成頁面絕對座標。

最容易出錯的地方

換行與空白的處理是關鍵。textarea 裡的 \n 必須換成 <br/>,連續空白必須用 &nbsp; 填補,否則瀏覽器會把空白合併,替身 div 的行數就對不上。另外替身 div 必須設 visibility: hidden 而非 display: none——後者根本不參與排版,量不到任何座標。

今天的替代方案

現在有兩個更省事的做法:textarea-caret-position 這類小型函式庫就是上述技巧的精簡版;而 getClientRects() 搭配 Selection API 在特定情境下也能拿到範圍。但老實說,上面這份手寫版本作為「如何量測文字排版」的教材價值更高——它示範了瀏覽器沒有提供 API 時,工程師如何用一個隱藏元素把答案「逼」出來。

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