<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <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>
<!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> <title>无标题页</title> </head> <body> <form name="form1" method="post" id="form1"> <a href="javascript:" onclick="SetContent(this.innerText)">用户名</a><br> <textarea name="txtTemp" rows="2" cols="20" id="txtTemp" onblur="onblurAction();" style="height:320px;700px;"></textarea> </form> </body> </html> <script type="text/javascript"> function SetContent(text) { txtTemp.focus(); var sel = document.selection.createRange(); sel.text=text; } function onblurAction() { txtTemp = event.srcElement; } </script>