Add a hyperlink to the selected content in the input box
Copy codeThe 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 = "<a href = '" + hyperlinks + "'target =' _ blank '> <B> <u> <font color =' #686600 '>" + selectedText + "</font> </u> </B> </a> ";
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 = "<a href = '" + hyperlinks + "'target =' _ blank '> <B> <u> <font color =' #686600 '>" + selectedText + "</font> </u> </B> </a> ";
}
}
Else {
Alert ("select the text to add link! ");
Return;
}
}