js操作輸入框中選擇內容兼容IE及其他主流瀏覽器
更新時間:2014年04月22日 17:28:33 作者:
這篇文章主要介紹了js如何操作輸入框中選擇的內容兼容IE及其他主流瀏覽器,需要的朋友可以參考下
工作中遇到需要給輸入框中選中的內容增加超鏈接
function addHref(des){
var selectedText="";
if(window.getSelection&&des != undefined){//兼容非IE瀏覽器,由于非IE瀏覽器需要給定操作的元素ID才可以獲取輸入元素中選中的內容,因此需要輸入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("請選擇需要添加鏈接的文字!");
return;
}
var hyperlinks=prompt("超鏈接地址:","");
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")){//IE中不需要ID
var range=document.selection.createRange();
var formerElement=range.parentElement();
if(formerElement.tagName!="TEXTAREA"){
alert("請在指定位置選擇需要添加超鏈接的文字!");
return;
}
selectedText=range.text;
var hyperlinks=prompt("超鏈接地址:","");
if(hyperlinks!=null){
range.text="<a href='"+hyperlinks+"' target='_blank'><b><u><font color='#686600'>" + selectedText + "</font></u></b></a>";
}
}
else{
alert("請選擇需要添加鏈接的文字!");
return;
}
}
復制代碼 代碼如下:
function addHref(des){
var selectedText="";
if(window.getSelection&&des != undefined){//兼容非IE瀏覽器,由于非IE瀏覽器需要給定操作的元素ID才可以獲取輸入元素中選中的內容,因此需要輸入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("請選擇需要添加鏈接的文字!");
return;
}
var hyperlinks=prompt("超鏈接地址:","");
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")){//IE中不需要ID
var range=document.selection.createRange();
var formerElement=range.parentElement();
if(formerElement.tagName!="TEXTAREA"){
alert("請在指定位置選擇需要添加超鏈接的文字!");
return;
}
selectedText=range.text;
var hyperlinks=prompt("超鏈接地址:","");
if(hyperlinks!=null){
range.text="<a href='"+hyperlinks+"' target='_blank'><b><u><font color='#686600'>" + selectedText + "</font></u></b></a>";
}
}
else{
alert("請選擇需要添加鏈接的文字!");
return;
}
}
相關文章
JavaScript中三個等號和兩個等號的區(qū)別(== 和 ===)淺析
javascript中比較運算符'=='與'==='可能大家用的比較多,但是大家對他的區(qū)別不是很清楚,接下來小編給大家介紹下js中三個等號和兩個等號的區(qū)別(== 和 ===),感興趣的朋友可以參考下2016-09-09js使用數(shù)組判斷提交數(shù)據(jù)是否存在相同數(shù)據(jù)
判斷提交數(shù)據(jù)是否存在相同數(shù)據(jù),在本文將為大家介紹使用數(shù)組做到這一點,感興趣的朋友可以參考下2013-11-11