Js operation input box to select content compatible with IE and other major browsers

  • 2020-03-30 02:43:26
  • OfStack

Work encountered the need to add hyperlinks to the input box selected content
 
function addHref(des){ 
var selectedText=""; 
if(window.getSelection&&des != undefined){//It is compatible with non-ie browsers. Since non-ie browsers need the element ID of a given operation to get the content selected by the input element, they need to enter an 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(" Please select the text to add the 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(" Please select the text in the specified location to add a hyperlink! "); 
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(" Please select the text to add the link! "); 
return; 
} 
} 

Related articles: