项目开发中需要计算textarea光标的开始位置与结束位置,以便于在指定位置插入文本。下面这段代码测试通过,能够得到光标的开始位置与结束位置。var er = document.selection.createRange(),start = 0,end = 0;
if(er.parentElement().id === this.id){ // create a selection of the whole textarea var er1 = document.body.createTextRange(); er1.moveToElementText(this); //两个range,一个是已经选择的text(er),一个是整个textarea(er1) //er1.compareEndPoints()比较两个端点,如果er1比er更往左(further to the left),则 //返回小于0的值,则er1往右移一点,直到两个er的start相同。 // calculate selection start point by moving beginning of er1 to beginning of er for (start = 0;er1.compareEndPoints('StartToStart',er) < 0;start++){ er1.moveStart('character', 1); } // get number of line breaks from textarea start to selection start and add them to start // 计算一下\n for (var i = 0; i <= start;i++){ if (this.value.charAt(i) == '\n'){ start++; } } // create a selection of the whole textarea var er1 = document.body.createTextRange(); er1.moveToElementText(this); // calculate selection end point by moving beginning of er1 to end of er for (end = 0;er1.compareEndPoints('StartToEnd',er) < 0;end++){ er1.moveStart('character',1); } // get number of line breaks from textarea start to selection end and add them to end for (var i = 0;i <= end;i++){ if (this.value.charAt(i) == '\n'){ end ++; } } }