This is a jquery plug-in. It is mainly used to insert a piece of text information to the cursor. This function sounds very simple, but it is not so easy to make it, mainly because of compatibility issues, later I checked a lot of information and found this short and sophisticated jquery plug-in. Let's share it with you.
(Function ($ ){
$. Fn. extend ({
InsertAtCaret: function (myValue ){
Var $ t = $ (this) [0];
If (document. selection ){
This. focus ();
Sel = document. selection. createRange ();
Sel. text = myValue;
This. focus ();
} Else if ($ t. selectionStart | $ t. selectionStart = '0 '){
Var startPos = $ t. selectionStart;
Var endPos = $ t. selectionEnd;
Var scrollTop = $ t. scrollTop;
$ T. value = $ t. value. substring (0, startPos) + myValue + $ t. value. substring (endPos, $ t. value. length );
This. focus ();
$ T. selectionStart = startPos + myValue. length;
$ T. selectionEnd = startPos + myValue. length;
$ T. scrollTop = scrollTop;
} Else {
This. value + = myValue;
This. focus ();
}
}
});
}) (JQuery );
Usage: $ ("select"). insertAtCaret ("text ");
If you are not used to this method, you can change it to a normal function, for example:
Function insertAtCaret (obj, myValue ){
Var $ t = obj [0];
If (document. selection ){
This. focus ();
Sel = document. selection. createRange ();
Sel. text = myValue;
This. focus ();
} Else if ($ t. selectionStart | $ t. selectionStart = '0 '){
Var startPos = $ t. selectionStart;
Var endPos = $ t. selectionEnd;
Var scrollTop = $ t. scrollTop;
$ T. value = $ t. value. substring (0, startPos) + myValue + $ t. value. substring (endPos, $ t. value. length );
This. focus ();
$ T. selectionStart = startPos + myValue. length;
$ T. selectionEnd = startPos + myValue. length;
$ T. scrollTop = scrollTop;
} Else {
This. value + = myValue;
This. focus ();
}
}
Usage is similar to the above: insertAtCaret imports a jquery object and the text to be inserted, insertAtCaret ($ ("select"), "text ");