【简介】本文主要实现获取textarea和input光标的像素位置,即光标的offsetLeft与offsetTop。可实现如下效果:

首先说明一下,在网上搜到的很多代码是如何获取输入光标位置的如下代码是如何获取光标的的字符位置,如对于串“He|llo World!”返回的是光标|前的字符数2,并不是光标在页面上的像素位置。当然,这段代码对于获取光标的像素位置能起到一定的辅助作用。

[javascript]  view plain copy
  1. // 获取光标在文本框的位置  
  2.     function _getFocus(elem) {  
  3.         var index = 0;  
  4.         if (document.selection) {// IE Support  
  5.             elem.focus();  
  6.             var Sel = document.selection.createRange();  
  7.             if (elem.nodeName === 'TEXTAREA') {//textarea  
  8.                 var Sel2 = Sel.duplicate();  
  9.                 Sel2.moveToElementText(elem);  
  10.                 var index = -1;  
  11.                 while (Sel2.inRange(Sel)) {  
  12.                     Sel2.moveStart('character');  
  13.                     index++;  
  14.                 };  
  15.             }  
  16.             else if (elem.nodeName === 'INPUT') {// input  
  17.                 Sel.moveStart('character', -elem.value.length);  
  18.                 index = Sel.text.length;  
  19.             }  
  20.         }  
  21.         else if (elem.selectionStart || elem.selectionStart == '0') { // Firefox support  
  22.             index = elem.selectionStart;  
  23.         }  
  24.         return (index);  
  25.     }  

对于IE浏览器,通过下面的代码1实现起来比较方便。

[javascript]  view plain copy
  1. //代码1  
  2. if (document.selection) {      
  3.     elem.focus();  
  4.     var Sel = document.selection.createRange();  
  5.     return {  
  6.         left: Sel.boundingLeft,  
  7.         top: Sel.boundingTop,  
  8.         bottom: Sel.boundingTop + Sel.boundingHeight  
  9.     };  
  10. }  

而对于firefox之类的浏览器则通过模拟来实现,如下图所示。首先通过拷贝输入区域的样式到一个div层(clone层),然后在此clone层之中的text子层添加光标之前的字符,并在text子层之后添加focus层,focus层中包含字符“|”来模拟光标,进而通过获取focus层的偏移量即可获得文本光标的像素坐标位置。