日期:2014-05-16  浏览次数:20241 次

js 问题,快疯了,帮帮忙.....
我想获取光标在某个文本框里的位置 ,效果图如下,最好兼容的,搞了好久都没整出来


------解决方案--------------------
HTML code


<!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">
/**
* 获取光标所在的字符位置
* @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>

------解决方案--------------------
http://blog.163.com/flying_heart/blog/static/9811907620093134156646/
------解决方案--------------------
http://blog.csdn.net/pillar0514/article/details/6653666
------解决方案--------------------
http://blog.csdn.net/pillar0514/article/details/6653666
------解决方案--------------------
http://www.xuanqi8.com/userlist/admin/newshow-959.html看看能不能帮到吧。
------解决方案--------------------
jCaret plugin
http://archive.plugins.jquery.com/project/jCaret