1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=GBK" />
5 <title>js获取光标位置</title>
6 <script type="text/javascript">
7 /**
8 * 获取光标所在的字符位置
9 * @param obj 要处理的控件, 支持文本域和输入框
10 * @author hotleave
11 */
12 function getPosition(obj){
13 //alert(obj.tagName);
14 var result = 0;
15 if(obj.selectionStart){ //非IE浏览器
16 result = obj.selectionStart
17 }else{ //IE
18 var rng;
19 if(obj.tagName == "TEXTAREA"){ //如果是文本域
20 rng = event.srcElement.createTextRange();
21 rng.moveToPoint(event.x,event.y);
22 }else{ //输入框
23 rng = document.selection.createRange();
24 }
25 rng.moveStart("character",-event.srcElement.value.length);
26 result = rng.text.length;
27 }
28 return result;
29 }
30
31 function getValue(obj){
32 var pos = getPosition(obj);
33 //alert(pos);
34 alert(obj.value.substr(0,pos)+" [这里是添加的内容] "+obj.value.substr(pos,obj.value.length));
35 }
36 </script>
37 </head>
38 <body>
39 <input type="text" value="你好,Amethyst!" onmouseup="getValue(this)" style="display:block" mce_style="display:block">
40 <textarea rows="6" cols="60" onmouseup="getValue(this)">Amethyst, 你好.