一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

js TextArea获取光标详解说明与实例

时间:2011-05-19 编辑:简简单单 来源:一聚教程网

可能许多朋友会对新浪微博和沪江碎碎里,敲入@时弹出用户列表的功能是如何实现的比较困惑。

其中,最难解决的问题应该就是获取当前光标据文本框的相对位置了。因为一个普通的<textarea>通过正常的途径是无法获取到的。

那怎么办呢~

第一步:创建一个普通的TextArea框,然后在TextArea外层套一个DIV(DIV的Position设为relative,到时候会根据这个div来定位弹出框的位置)

第二步:创建一个与TextArea 同样尺寸的DIV(这个DIV在什么位置无所谓)在此我先称其为div_textarea

注意:该DIV的所使用的字体,文字的大小,行间距等都要与文本框里所使用的一致。然后将 div_textarea 的Position也设为relative,visibility设为hidden(这个是背后操作的,当然不能让人看到啦)

说明:该DIV的作用就是用来获取输入@时光标的相对位置的。 

结构如下:

第三步:脚本获取相对位置

操作: 当用户输入@了,通过脚本自动将文本框里的这些字符复制到 div_textarea 里,然后获取当前文本框光标在第几个字的后面,获得后在@相当于文本框的同样位置,插入(该span和@的相对位置应该是一样的)。 

插入完后,那只要获得这个span离 div_textarea 的相对位置,就知道@离文本框的位置了。

获得相对位置了

看个js实现代码

所以还是原版放在这里吧。

varstart=0;  

varend=0;  

functionadd(){  

vartextBox=document.getElementById("ta");  

varpre=textBox.value.substr(0,start);  

varpost=textBox.value.substr(end);  

textBox.value=pre+document.

getElementById("inputtext").value+post;  

}  

functionsavePos(textBox){  

//如果是Firefox(1.5)的话,方法很简单  

if(typeof(textBox.selectionStart)=="number"){  

start=textBox.selectionStart;  

end=textBox.selectionEnd;  

}  

//下面是IE(6.0)的方法,麻烦得很,还要计算上'n'  

elseif(document.selection){  

varrange=document.selection.createRange();  

if(range.parentElement().id==textBox.id){  

//createaselectionofthewholetextarea  

varrange_all=document.body.createTextRange();  

range_all.moveToElementText(textBox);  

//两个range,一个是已经选择的text(range),  

一个是整个textarea(range_all)  

//range_all.compareEndPoints()比较两个端点,  

如果range_all比range更往左(furthertotheleft),  

则//返回小于0的值,则range_all往右移一点,直到两个range的start相同。  

//calculateselectionstartpointbymoving

beginningofrange_alltobeginningofrange  

for(start=0;range_all.compareEndPoints

("StartToStart",range)<0;start++)range_all.moveStart('character',1);  

//getnumberoflinebreaksfromtextareastarttose

lectionstartandaddthemtostart  

//计算一下n  

for(vari=0;i<=start;i++){  

if(textBox.value.charAt(i)=='n')  

start++;  

}  

//createaselectionofthewholetextarea  

varrange_all=document.body.createTextRange();  

range_all.moveToElementText(textBox);  

//calculateselectionendpointbymovingbeginningofrange_alltoendofrange  

for(end=0;range_all.compareEndPoints('StartToEnd',range)<0;end++)  

range_all.moveStart('character',1);  

//getnumberoflinebreaksfromtextareastarttoselectionendandaddthemtoend  

for(vari=0;i<=end;i++){  

if(textBox.value.charAt(i)=='n')  

end++;  

}  

}  

}  

document.getElementById("start").value=start;  

document.getElementById("end").value=end;  

}  

 

 

 


下面是在页面中调用js代码的方法:

 

cellspacing="0"cellpadding="0"> 

 

start:

id="start"size="3"/> 

end:

id="end"size="3"/> 

 

 

 

onKeyup="savePos(this)" 

onmousedown="savePos(this)" 

onmouseup="savePos(this)" 

onfocus="savePos(this)" 

rows="14"cols="50"> 

 

 

 

id="inputtext"/> 

onClick="add()"value="AddText"/> 

 

 

 

热门栏目