对于在TextArea中光标位置插入值,很多人都可能会想到用
document.selection.createRange().text=”要求插入的值” 的方法,但是对于一些在textArea中的光标位置插入值时,对于插入的值可能会要求在一个弹出窗体中,或者javascript做的弹出Div中进行编辑后或者相关操作(如录入一些条件后再插入时)这时候TextArea中的光标位置就不是原来的了,而且有可能无法得到正确的插入位置,可以考虑采用以下的办法解决。注本实例中js的写法,采用了prototype.js对应的写法,兼容IE与FireFox
在TextArea中onclick及onbluer时存下对应的textArea中原来的光标位置值,然后在插入值时,用记录的位置值去插入。
例如:
var ContentCurrentPostion=null; //记录当前位置,如果是IE记录的应该是一个rang范围,firefox则记录的是一个位置值
/****记录插入位置***/
var GetTextAreaPostion=function(obj)
{
if(document.selection)
{
obj.focus();
ContentCurrentPostion=document.selection.createRange();
}
else if(obj.selectionStart||obj.selectionStart=='0'){
var startPos=obj.selectionStart;
var endPos=obj.selectionEnd;
ContentCurrentPostion=new Object();
ContentCurrentPostion.startPos=startPos;
ContentCurrentPostion.endPos=endPos;
}
else
{
ContentCurrentPostion=null;
}
}
<textarea class="fm_textarea_record" id="AddContent" name="Content" cols="50" rows="4" οnclick="GetTextAreaPostion(this)"></textarea>
比如说在弹出的Div中点击一个按钮时,或者页面上点击其它按钮插入值时调用如下方法:
var SetContent=function(value,id)
{
var str=value;
if(ContentCurrentPostion!=null)
{
$(id).focus();
if(document.selection)
{
ContentCurrentPostion.text=str; }
else
{
var startPos=ContentCurrentPostion.startPos;
var endPos=ContentCurrentPostion.endPos;
$(id).value=$(id).value.substring(0,startPos)+str+$(id).value.substring(endPos,$(id).value.length);
}
}
else
{
$(id).value+=str;
}
};