在輸入框光標位置顯示自動完成下拉、表情選擇器、校驗提示浮層等,需要獲取光標相對文檔的 `left`、`top`、`bottom` 坐標。主流瀏覽器差異大,需兼容 IE(`document.selection`)與現代瀏覽器(`selectionStart`/`getBoundingClientRect`)。
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>
若僅需支持現代瀏覽器(不含 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 方案,舊項目維護請用完整兼容版。