Insert a string at the cursor to implement code compatibility with IE and Firefox

Source: Internet
Author: User

Copy codeThe Code is as follows:
// Insert a string at the cursor
// MyField text box object
// The value to insert
Function insertAtCursor (myField, myValue)
{
// IE support
If (document. selection)
{
MyField. focus ();
Sel = document. selection. createRange ();
Sel. text = myValue;
Sel. select ();
}
// MOZILLA/NETSCAPE support
Else if (myField. selectionStart | myField. selectionStart = '0 ')
{
Var startPos = myField. selectionStart;
Var endPos = myField. selectionEnd;
// Save scrollTop before insert
Var restoreTop = myField. scrollTop;
MyField. value = myField. value. substring (0, startPos) + myValue + myField. value. substring (endPos, myField. value. length );
If (restoreTop> 0)
{
// Restore previous scrollTop
MyField. scrollTop = restoreTop;
}
MyField. focus ();
MyField. selectionStart = startPos + myValue. length;
MyField. selectionEnd = startPos + myValue. length;
} Else {
MyField. value + = myValue;
MyField. focus ();
}
}

The Demo code is as follows:

[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.