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;
}
}