萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 獲取輸入框光標在頁面上的絕對坐標(跨瀏覽器兼容)

需求場景

在輸入框光標位置顯示自動完成下拉、表情選擇器、校驗提示浮層等,需要獲取光標相對文檔的 `left`、`top`、`bottom` 坐標。主流瀏覽器差異大,需兼容 IE(`document.selection`)與現代瀏覽器(`selectionStart`/`getBoundingClientRect`)。

核心庫代碼(封裝為 kingwolfofsky 對象)

var kingwolfofsky = {
  /**
   * 獲取輸入框光標在頁面中的絕對坐標
   * @param {HTMLInputElement|HTMLTextAreaElement} elem - 輸入框元素
   * @returns {Object} { left, top, bottom }
   */
  getInputPositon: function(elem) {
    // --- IE 8/9/10/11 (document.selection) ---
    if (document.selection) {
      elem.focus(); // 必須先聚焦
      var sel = document.selection.createRange();
      return {
        left: sel.boundingLeft,
        top: sel.boundingTop,
        bottom: sel.boundingTop + sel.boundingHeight
      };
    }
    
    // --- 現代瀏覽器 (selectionStart + 克隆元素測量) ---
    var that = this;
    var cloneDivKey = '_cloneDiv', cloneLeftKey = '_cloneLeft', cloneFocusKey = '_cloneFocus';
    var noneSpan = ' '; // 佔位空格
    
    // 獲取或創建克隆容器
    var div = elem[cloneDivKey] || document.createElement('div');
    var focusSpan = elem[cloneFocusKey] || document.createElement('span');
    var leftSpan = elem[cloneLeftKey] || document.createElement('span');
    
    if (!elem[cloneDivKey]) {
      // 首次初始化
      elem[cloneDivKey] = div;
      elem[cloneFocusKey] = focusSpan;
      elem[cloneLeftKey] = leftSpan;
      
      div.appendChild(leftSpan);
      div.appendChild(focusSpan);
      document.body.appendChild(div);
      
      focusSpan.innerHTML = '|'; // 光標標記
      focusSpan.style.cssText = 'display:inline-block;width:0;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;';
    }
    
    // 同步克隆容器位置
    var offset = this._offset(elem);
    div.style.left = offset.left + 'px';
    div.style.top = offset.top + 'px';
    
    // 獲取光標索引
    var index = this._getFocus(elem);
    
    // 設置光標前文本(轉義 HTML、換行、空格)
    var text = elem.value.substring(0, index)
      .replace(/&/g, '&')
      .replace(//g, '>')
      .replace(/\n/g, '
') .replace(/ /g, noneSpan); leftSpan.innerHTML = text; // 顯示光標標記並測量位置 focusSpan.style.display = 'inline-block'; var focusOffset = this._offset(focusSpan); focusSpan.style.display = 'none'; return { left: focusOffset.left, top: focusOffset.top, bottom: focusOffset.bottom }; }, // --- 輔助方法 --- // 克隆元素所有計算樣式生成類名 _cloneStyle: function(elem) { var cacheKey = '_cloneClassName'; if (elem[cacheKey]) return elem[cacheKey]; var cssText = []; var s = getComputedStyle(elem); var skip = /^(content|outline|outlineWidth)$/; // 跳過特殊屬性 for (var i = 0; i < s.length; i++) { var name = s[i]; if (skip.test(name)) continue; var val = s.getPropertyValue(name); if (val) { cssText.push(name + ':' + val + ';'); } } var className = 'cursorClone_' + Date.now() + '_' + Math.random().toString(36).substr(2, 6); this._addHeadStyle('.' + className + '{' + cssText.join('') + '}'); elem[cacheKey] = className; return className; }, // 向 head 插入 style _addHeadStyle: function(css) { var style = this._styleEl || (this._styleEl = document.createElement('style')); document.head.appendChild(style); style.sheet ? style.sheet.cssText += css : style.appendChild(document.createTextNode(css)); }, // 獲取光標索引 _getFocus: function(elem) { if (document.selection) { // IE elem.focus(); var sel = document.selection.createRange(); if (elem.nodeName === 'TEXTAREA') { var sel2 = sel.duplicate(); sel2.moveToElementText(elem); var index = -1; while (sel2.inRange(sel)) { sel2.moveStart('character'); index++; } return index; } else { // INPUT sel.moveStart('character', -elem.value.length); return sel.text.length; } } else if (typeof elem.selectionStart === 'number') { // 現代 return elem.selectionStart; } return 0; }, // 獲取元素絕對位置 (getBoundingClientRect + 滾動偏移) _offset: function(elem) { var rect = elem.getBoundingClientRect(); var doc = elem.ownerDocument; var docEl = doc.documentElement; var body = doc.body; var clientTop = docEl.clientTop || body.clientTop || 0; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft; return { left: rect.left + scrollLeft - clientLeft, top: rect.top + scrollTop - clientTop, right: rect.right + scrollLeft - clientLeft, bottom: rect.bottom + scrollTop - clientTop }; } };

調用示例

<textarea id="editor" rows="5" cols="40">輸入文本...</textarea>
<div id="tooltip" style="position:absolute;background:#333;color:#fff;padding:5px 10px;border-radius:4px;display:none;">提示內容</div>

<script>
var editor = document.getElementById('editor');
var tooltip = document.getElementById('tooltip');

editor.addEventListener('keyup', function() {
  var pos = kingwolfofsky.getInputPositon(editor);
  tooltip.style.left = pos.left + 'px';
  tooltip.style.top = pos.bottom + 5 + 'px'; // 光標下方 5px
  tooltip.style.display = 'block';
});

editor.addEventListener('blur', function() {
  tooltip.style.display = 'none';
});
</script>

關鍵技術難點解析

  1. IE TextRange 座標:`boundingLeft/Top/Height` 直接給出光標矩形,最簡單準確。
  2. 現代瀏覽器無原生 API:採用「克隆元素 + 模擬光標」方案:
    • 克隆輸入框樣式(字體、行高、padding、border 等)確保渲染一致。
    • 將光標前文本注入克隆容器,末尾加 `|` 標記。
    • 測量 `|` 的位置即為光標位置。
  3. 白空間處理:`white-space: pre-wrap` 保留換行和連續空格,空格用 ` ` 佔位防止合併。
  4. 滾動容器支持:`_offset` 使用 `getBoundingClientRect` + 文檔滾動偏移,自動支持任意滾動祖先。
  5. 性能優化:克隆容器緩存復用,樣式類名緩存,避免重複創建 DOM 和 style 標籤。

現代替代方案(輕量、無依賴)

若僅需支持現代瀏覽器(不含 IE),可使用更簡潔的方案:

function getCursorPositionModern(elem) {
  // 創建一個隱藏的 mirror div
  var mirror = document.createElement('div');
  var style = getComputedStyle(elem);
  // 複製關鍵樣式
  ['font', 'font-size', 'font-family', 'font-weight', 'line-height', 'letter-spacing', 
   'padding', 'border', 'box-sizing', 'white-space', 'word-wrap', 'word-break'].forEach(function(p) {
    mirror.style[p] = style[p];
  });
  mirror.style.position = 'absolute';
  mirror.style.visibility = 'hidden';
  mirror.style.top = '-9999px';
  document.body.appendChild(mirror);
  
  var text = elem.value.substring(0, elem.selectionStart)
    .replace(/&/g, '&').replace(//g, '>')
    .replace(/\n/g, '
').replace(/ /g, ' '); mirror.innerHTML = text + '|'; var marker = document.getElementById('cursor-marker'); var rect = marker.getBoundingClientRect(); document.body.removeChild(mirror); return { left: rect.left + window.scrollX, top: rect.top + window.scrollY, bottom: rect.bottom + window.scrollY }; }

結語

獲取光標絕對坐標是構建豐富文本編輯器、智能提示、上下文菜單的基礎設施。本文提供的方案兼容 IE6+ 及所有現代瀏覽器,通過克隆渲染實現像素級精確。現代項目中可優先使用輕量 mirror 方案,舊項目維護請用完整兼容版。

copyright © 萬盛學電腦網 all rights reserved