【简介】本文主要实现获取textarea和input光标的像素位置,即光标的offsetLeft与offsetTop。可实现如下效果:
首先说明一下,在网上搜到的很多代码是如何获取输入光标位置的如下代码是如何获取光标的的字符位置,如对于串“He|llo World!”返回的是光标|前的字符数2,并不是光标在页面上的像素位置。当然,这段代码对于获取光标的像素位置能起到一定的辅助作用。
- // 获取光标在文本框的位置
- function _getFocus(elem) {
- var index = 0;
- if (document.selection) {// IE Support
- elem.focus();
- var Sel = document.selection.createRange();
- if (elem.nodeName === 'TEXTAREA') {//textarea
- var Sel2 = Sel.duplicate();
- Sel2.moveToElementText(elem);
- var index = -1;
- while (Sel2.inRange(Sel)) {
- Sel2.moveStart('character');
- index++;
- };
- }
- else if (elem.nodeName === 'INPUT') {// input
- Sel.moveStart('character', -elem.value.length);
- index = Sel.text.length;
- }
- }
- else if (elem.selectionStart || elem.selectionStart == '0') { // Firefox support
- index = elem.selectionStart;
- }
- return (index);
- }
对于IE浏览器,通过下面的代码1实现起来比较方便。
- //代码1
- if (document.selection) {
- elem.focus();
- var Sel = document.selection.createRange();
- return {
- left: Sel.boundingLeft,
- top: Sel.boundingTop,
- bottom: Sel.boundingTop + Sel.boundingHeight
- };
- }
而对于firefox之类的浏览器则通过模拟来实现,如下图所示。首先通过拷贝输入区域的样式到一个div层(clone层),然后在此clone层之中的text子层添加光标之前的字符,并在text子层之后添加focus层,focus层中包含字符“|”来模拟光标,进而通过获取focus层的偏移量即可获得文本光标的像素坐标位置。
转载于:https://blog.51cto.com/everthinking/1153216