javascript| cursor
Little brother recently in writing an online editor, UBB version of, because no pop-up window, so, in addition to the code, can only be added to the end of the textarea, can not be inserted before the cursor, so in the online crazy looking for information, time does not bear a conscientious, I finally found out how to get the position in the textarea, but if there is a lot of content in the textarea, it will appear very flashing. Its code is as follows.
function GetPos (obj)
{
Obj.focus ();
var workrange=document.selection.createrange ();
Obj.select ();
var allrange=document.selection.createrange ();
Workrange.setendpoint ("Starttostart", Allrange);
var len=workrange.text.length;
Workrange.collapse (FALSE);
Workrange.select ();
return Len;
}
When the problem comes out, the obj.select () will cause flicker and the scroll bar cannot be returned to position. So the younger brother according to their own needs, will be rewritten as follows:
function Getcaret (Zysrid)
{
var txb = document.getElementById (Zysrid);//Get object based on ID
var pos = 0;//Set initial position
Txb.focus ()//input box to get focus, this sentence can not be less, or the back will be wrong, blood lesson.
var s = txb.scrolltop;//Gets the scroll bar position
var r = Document.selection.createRange ();//Create Document Selection Object
var t = txb.createtextrange ();//Create an input Box text object
T.collapse (TRUE);//move cursor to head
T.select ()//display cursor, this should not be less, otherwise, the cursor does not move to the end. I didn't know that. More than 10 minutes.
var j = Document.selection.createRange ();//Create document Selection object for new cursor position
R.setendpoint ("Starttostart", j); Create an object between the previous document Selection object and the new object, damn it, it's not good for me to explain. I'm interested in seeing the MSDN information myself.
var str = r.text;//Gets the text of the object
var re = new RegExp ("[\\n]", "G")//filter swap line characters, otherwise your text will have a problem, it will be longer than the actual length of your text. I'm dead. I say I get the number is always longer than my actual length.
str = str.replace (Re, "");/filter
pos = str.length;//Gets the length. That's where the cursor is.
R.collapse (FALSE);
R.select ()//To restore the cursor to its previous position
Txb.scrolltop = s;//Restores the scroll bar to its previous position
}
Setting the cursor function
function Setcaret (Id,pos)
{
var textbox = document.all (ID);
var r = Textbox.createtextrange ();
R.collapse (TRUE);
R.movestart (' character ', POS);
R.select ();
}
In fact, this is not difficult, but do not know the time, will be dead. In order to achieve this effect, I've been trying for about five hours, damn it. I hope this is helpful to some brothers.