js获取光标位置


JavaScript #光标位置2012-07-14 21:12

例子一:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK" />
<title>js获取光标位置</title>
<script type="text/javascript">
/** http://yige.org
* 获取光标所在的字符位置
* @param obj 要处理的控件, 支持文本域和输入框
* @author hotleave
*/
function getPosition(obj){
//alert(obj.tagName);
var result = 0;
if(obj.selectionStart){ //非IE浏览器
   result = obj.selectionStart
}else{ //IE
   var rng;
   if(obj.tagName == "TEXTAREA"){ //如果是文本域
    rng = event.srcElement.createTextRange();
    rng.moveToPoint(event.x,event.y);
   }else{ //输入框
    rng = document.selection.createRange();
   }
   rng.moveStart("character",-event.srcElement.value.length);
   result = rng.text.length;
}
return result;
}
function getValue(obj){
     var pos = getPosition(obj);
//alert(pos);
alert(obj.value.substr(0,pos)+" [这里是添加的内容] "+obj.value.substr(pos,obj.value.length));
}
</script>
</head>
<body>
<input type="text" value="你好,Amethyst!" onmouseup="getValue(this)" style="display:block">
<textarea rows="6" cols="60" onmouseup="getValue(this)">Amethyst, 你好.</textarea>
</body>
</html>
例子二:

<html> 
<textarea   rows="7"   cols="49"   id="box"   onclick=tellPoint()> 
fasdfsdafsdafsafsadsdfsdfasfsafdsadfsadfsaf 
     </textarea> 
     <script   language="javascript"> 
   function   tellPoint() 
   { 
      var   rng   =   event.srcElement.createTextRange(); 
      rng.moveToPoint(event.x,event.y); 
    rng.moveStart("character",-event.srcElement.value.length); 
     pnum.value   =   rng.text.length; 
    } 
   </script> <p></p>                     
   光标位置:<input   type="text"   value="0"   id="pnum"   size="8">     
</html>


相关文章

粤ICP备11097351号-1