<html> |
<head> |
<meta http-equiv= "Content-Type" content= "text/html; charset=gb2312" /> |
<title>js获得光标在文本框中的位置(text/textarea)</title> |
<script type= "text/javascript" > |
function getCursorPosition(obj){ |
var evt =window.event?window.event:getTa1CursorPosition.caller.arguments[0]; |
var oTa1 = document.getElementById(obj); |
try { |
if (oTa1.value== "" ) return 0; |
var cursurPosition=-1; |
if (oTa1.selectionStart){ //非IE浏览器 |
cursurPosition= oTa1.selectionStart; |
} else { //IE |
var rngSel = document.selection.createRange(); //建立选择域 |
var rngTxt = oTa1.createTextRange(); //建立文本域 |
var flag = rngSel.getBookmark(); //用选择域建立书签 |
rngTxt.collapse(); //瓦解文本域到开始位,以便使标志位移动 |
rngTxt.moveToBookmark(flag); //使文本域移动到书签位 |
rngTxt.moveStart( 'character' ,-oTa1.value.length); //获得文本域左侧文本 |
cursurPosition = rngTxt.text.replace(/\r\n/g, '' ).length; //替换回车换行符 |
} |
return cursurPosition; |
} |
catch (e){ |
return oTa1.value.length; |
} |
|
} |
function getValue(obj){ |
var pos = getCursorPosition(obj); |
alert(obj.value.substr(0,pos)+ "[输入内容]" +obj.value.substr(pos,obj.value.length)); |
} |
</script> |
</head> |
<body> |
<input type= "text" value= "HELLO jb51" onmouseup= "getValue(this)" style= "display:block" > |
<textarea rows= "6" cols= "60" onmouseup= "getValue(this)" >jb51 HELLO!</textarea> |
</body> |
</html> |