天天看點

JavaScript擷取文本框光标的像素位置2

[html]

 view plaincopy

  1. var kingwolfofsky = {  
  2.     /**  
  3.     * 擷取輸入光标在頁面中的坐标  
  4.     * @param        {HTMLElement}   輸入框元素          
  5.     * @return       {Object}        傳回left和top,bottom  
  6.     */  
  7.     getInputPositon: function (elem) {  
  8.         if (document.selection) {   //IE Support  
  9.             elem.focus();  
  10.             var Sel = document.selection.createRange();  
  11.             return {  
  12.                 left: Sel.boundingLeft,  
  13.                 top: Sel.boundingTop,  
  14.                 bottom: Sel.boundingTop + Sel.boundingHeight  
  15.             };  
  16.         } else {  
  17.             var that = this;  
  18.             var cloneDiv = '{$clone_div}', cloneLeft = '{$cloneLeft}', cloneFocus = '{$cloneFocus}', cloneRight = '{$cloneRight}';  
  19.             var none = '<span style="white-space:pre-wrap;"> </span>';  
  20.             var div = elem[cloneDiv] || document.createElement('div'), focus = elem[cloneFocus] || document.createElement('span');  
  21.             var text = elem[cloneLeft] || document.createElement('span');  
  22.             var offset = that._offset(elem), index = this._getFocus(elem), focusOffset = { left: 0, top: 0 };  
  23.             if (!elem[cloneDiv]) {  
  24.                 elem[cloneDiv] = div, elem[cloneFocus] = focus;  
  25.                 elem[cloneLeft] = text;  
  26.                 div.appendChild(text);  
  27.                 div.appendChild(focus);  
  28.                 document.body.appendChild(div);  
  29.                 focus.innerHTML = '|';  
  30.                 focus.style.cssText = 'display:inline-block;width:0px;overflow:hidden;z-index:-100;word-wrap:break-word;word-break:break-all;';  
  31.                 div.className = this._cloneStyle(elem);  
  32.                 div.style.cssText = 'visibility:hidden;display:inline-block;position:absolute;z-index:-100;word-wrap:break-word;word-break:break-all;overflow:hidden;';  
  33.             div.style.left = this._offset(elem).left + "px";  
  34.             div.style.top = this._offset(elem).top + "px";  
  35.             var strTmp = elem.value.substring(0, index).replace(/</g, '<').replace(/>/g, '>').replace(/\n/g, '<br/>').replace(/\s/g, none);  
  36.             text.innerHTML = strTmp;  
  37.             focus.style.display = 'inline-block';  
  38.             try { focusOffset = this._offset(focus); } catch (e) { };  
  39.             focus.style.display = 'none';  
  40.                 left: focusOffset.left,  
  41.                 top: focusOffset.top,  
  42.                 bottom: focusOffset.bottom  
  43.         }  
  44.     },  
  45.     // 克隆元素樣式并傳回類  
  46.     _cloneStyle: function (elem, cache) {  
  47.         if (!cache && elem['${cloneName}']) return elem['${cloneName}'];  
  48.         var className, name, rstyle = /^(number|string)$/;  
  49.         var rname = /^(content|outline|outlineWidth)$/; //Opera: content; IE8:outline && outlineWidth  
  50.         var cssText = [], sStyle = elem.style;  
  51.         for (name in sStyle) {  
  52.             if (!rname.test(name)) {  
  53.                 val = this._getStyle(elem, name);  
  54.                 if (val !== '' && rstyle.test(typeof val)) { // Firefox 4  
  55.                     name = name.replace(/([A-Z])/g, "-$1").toLowerCase();  
  56.                     cssText.push(name);  
  57.                     cssText.push(':');  
  58.                     cssText.push(val);  
  59.                     cssText.push(';');  
  60.                 };  
  61.         };  
  62.         cssText = cssText.join('');  
  63.         elem['${cloneName}'] = className = 'clone' + (new Date).getTime();  
  64.         this._addHeadStyle('.' + className + '{' + cssText + '}');  
  65.         return className;  
  66.     // 向頁頭插入樣式  
  67.     _addHeadStyle: function (content) {  
  68.         var style = this._style[document];  
  69.         if (!style) {  
  70.             style = this._style[document] = document.createElement('style');  
  71.             document.getElementsByTagName('head')[0].appendChild(style);  
  72.         style.styleSheet && (style.styleSheet.cssText += content) || style.appendChild(document.createTextNode(content));  
  73.     _style: {},  
  74.     // 擷取最終樣式  
  75.     _getStyle: 'getComputedStyle' in window ? function (elem, name) {  
  76.         return getComputedStyle(elem, null)[name];  
  77.     } : function (elem, name) {  
  78.         return elem.currentStyle[name];  
  79.     // 擷取光标在文本框的位置  
  80.     _getFocus: function (elem) {  
  81.         var index = 0;  
  82.         if (document.selection) {// IE Support  
  83.             if (elem.nodeName === 'TEXTAREA') {//textarea  
  84.                 var Sel2 = Sel.duplicate();  
  85.                 Sel2.moveToElementText(elem);  
  86.                 var index = -1;  
  87.                 while (Sel2.inRange(Sel)) {  
  88.                     Sel2.moveStart('character');  
  89.                     index++;  
  90.             }  
  91.             else if (elem.nodeName === 'INPUT') {// input  
  92.                 Sel.moveStart('character', -elem.value.length);  
  93.                 index = Sel.text.length;  
  94.         else if (elem.selectionStart || elem.selectionStart == '0') { // Firefox support  
  95.             index = elem.selectionStart;  
  96.         return (index);  
  97.     // 擷取元素在頁面中位置  
  98.     _offset: function (elem) {  
  99.         var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement;  
  100.         var clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0;  
  101.         var top = box.top + (self.pageYOffset || docElem.scrollTop) - clientTop, left = box.left + (self.pageXOffset || docElem.scrollLeft) - clientLeft;  
  102.         return {  
  103.             left: left,  
  104.             top: top,  
  105.             right: left + box.width,  
  106.             bottom: top + box.height  
  107.     }  
  108. };  
  109. function getPosition(ctrl) {  
  110.     var p = kingwolfofsky.getInputPositon(ctrl);  
  111.     document.getElementById('show').style.left = p.left + "px";  
  112.     document.getElementById('show').style.top = p.bottom + "px";  
  113. }