Select Content compatible with IE and other mainstream browsers in the js operation input box _ javascript skills

Source: Internet
Author: User
This article mainly introduces how to use JavaScript to operate the content selected in the input box to be compatible with IE and other mainstream browsers. For more information, see Add a hyperlink to the content selected in the input box.

The Code is as follows:


Function addHref (des ){
Var selectedText = "";
If (window. getSelection & des! = Undefined) {// compatible with non-ie browsers. Because a non-IE browser needs to specify the operation element ID to obtain the selected content in the input element, you need to enter the ID

Var textField = document. getElementById (des );
Var selectionStart = textField. selectionStart;
Var selectionEnd = textField. selectionEnd;
If (selectionStart! = Undefined & selectionEnd! = Undefined ){
SelectedText = textField. value. substring (selectionStart, selectionEnd );
}
If (selectedText = ""){
Alert ("select the text to add link! ");
Return;
}
Var hyperlinks = prompt ("hyperlink address :","");
If (hyperlinks! = Null ){
Var replaceString =""+ SelectedText +"";
TmpStr = textField. value;
TextField. value = tmpStr. substring (0, selectionStart) + replaceString + tmpStr. substring (selectionEnd, tmpStr. length );
}
}
Else if (document. selection) & (document. selection. type = "Text") {// ID is not required in IE
Var range = document. selection. createRange ();
Var formerElement = range. parentElement ();
If (formerElement. tagName! = "TEXTAREA "){
Alert ("select the text to add hyperlink at the specified location! ");
Return;
}
SelectedText = range. text;
Var hyperlinks = prompt ("hyperlink address :","");
If (hyperlinks! = Null ){
Range. text =""+ SelectedText +"";
}
}
Else {
Alert ("select the text to add link! ");
Return;
}
}

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.