The example in this article summarizes the way JavaScript sets the text box cursor. Share to everyone for your reference, specific as follows:
For text
Get cursor position
function Getcaret (textbox) {
var control = document.activeelement;
Textbox.focus ();
var rang = Document.selection.createRange ();
Rang.setendpoint ("Starttostart", Textbox.createtextrange ())
control.focus ();
return rang.text.length;
}
For textarea
function Getcaret (Zysrid)
{
var txb = document.getElementById (Zysrid);//Get Object
var pos = 0;//Set initial position based on ID
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 position of the scroll bar
var r = document.selection.createRange ();//Create document Select Object
var t = Txb.createtextrange ()//Create the Input Box text object
T.collapse (TRUE);//move the cursor to the end
T.select (), or display the cursor, this should not be less, otherwise, The cursor does not move to the end. I didn't know that for more than 10 minutes.
var j = document.selection.createRange ()//Create a document Selection object for the new cursor position
r.setendpoint (" Starttostart ", j);//Create an object between the previous document Selection object and the new object, damn it, I'm not very good at explaining it. I'm interested in seeing the MSDN information.
var str = r.text;//Get the text
of an 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;//get length. That is, the position of the cursor
r.collapse (false);
R.select ()//returns 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 ();
}
More readers interested in JavaScript-related content can view the site topics: "JavaScript Search Algorithm Skills Summary", "JavaScript data structure and algorithm skills summary", "JavaScript traversal algorithm and Skills summary", " A summary of JSON manipulation techniques in JavaScript, a summary of JavaScript switching effects and techniques, a summary of JavaScript animation effects and techniques, JavaScript errors and debugging tips, and a summary of JavaScript mathematical operational usage
I hope this article will help you with JavaScript programming.