DIV CSS 佈局教程網

獲取輸入框中光標坐標的跨瀏覽器方案
編輯:關於JavaScript     

想在輸入框下方做一個隨光標位置浮動的提示層,就必須先知道光標在頁面中的準確坐標。IE 提供了 document.selection 可以直接拿到範圍邊界,其他瀏覽器則要用一個「克隆元素」的技巧來間接測量。

思路

  1. 把輸入框光標之前的文本取出來,放進一個隱藏的克隆 div 中。
  2. 在文本末尾插入一個寬度為 0 的 <span> 作為標記。
  3. 讀取這個 span 的頁面坐標,就是光標位置。
  4. 克隆 div 必須複製原輸入框的字體、字號、寬度、行高等樣式,否則換行位置會不一致。

核心實現

var kingwolfofsky = {

    /**
     * 獲取輸入光標在頁面中的坐標
     * @param {HTMLElement} elem 輸入框元素
     * @return {Object} 返回 left、top、bottom
     */
    getInputPositon: function (elem) {
        if (document.selection) {
            // IE:直接用 selection 的邊界屬性
            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";

            // 光標前的文本,換行與空白需要還原成 HTML
            var strTmp = elem.value.substring(0, index)
                .replace(/</g, '<').replace(/>/g, '>')
                .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
            };
        }
    },

    // 克隆元素樣式並返回生成的類名
    _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, ':', val, ';');
                }
            }
        }

        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);
                var 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') {
            // Firefox 等支持 selectionStart 的瀏覽器
            index = elem.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,
            clientLeft = docElem.clientLeft || body.clientLeft || 0;

        var top = box.top + (self.pageYOffset || docElem.scrollTop) - clientTop,
            left = box.left + (self.pageXOffset || docElem.scrollLeft) - clientLeft;

        return {
            left: left, top: top,
            right: left + box.width, bottom: top + box.height
        };
    }
};

// 封裝一個便於調用的函數
function getPosition(ctrl) {
    var p = kingwolfofsky.getInputPositon(ctrl);
    document.getElementById('show').style.left = p.left + "px";
    document.getElementById('show').style.top = p.bottom + "px";
}

調用方式

var elem = document.getElementById('控件ID');
var p = kingwolfofsky.getInputPositon(elem);

p.left;     // 光標橫坐標
p.top;      // 光標縱坐標
p.bottom;   // 光標底部坐標,常用來定位提示層

幾個關鍵細節

  • 克隆時要排除 content、outline、outlineWidth 這幾個屬性,它們在不同瀏覽器下取值異常,會污染生成的樣式。
  • 橫坐標計算依賴文本換行與原輸入框完全一致,因此克隆元素的寬度必須和原元素相同——實踐中這一點最容易出偏差。
  • IE 分支中 textarea 與 input 的取值方式不同,需要分別處理。
  • 每次調用都會重寫克隆元素的內容並讀取一次 getBoundingClientRect,屬於強制重排,輸入事件裡頻繁調用要注意性能,可做節流。
  • ES5 之後有了更簡潔的方案:用 <textarea> 的 setSelectionRange 配合鏡像 div 仍是主流做法,而新興的 Caret Position API 尚不完善,克隆法至今依然實用。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved