手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >js操作输入框中选择内容兼容IE及其他主流浏览器
js操作输入框中选择内容兼容IE及其他主流浏览器
摘要:工作中遇到需要给输入框中选中的内容增加超链接复制代码代码如下:functionaddHref(des){varselectedText=""...

工作中遇到需要给输入框中选中的内容增加超链接

复制代码 代码如下:

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;

}

}

【js操作输入框中选择内容兼容IE及其他主流浏览器】相关文章:

原生js实现的贪吃蛇网页版游戏完整实例

nodejs调试cmd命令实现复制目录

jQuery实现返回顶部效果的方法

jQuery常用知识点总结以及平时封装常用函数

jQuery处理图片加载失败的常用方法

发现的以前不知道的函数

滚动效果

非常酷的有农历的日历挂历!

jquery插件validation实现验证身份证号等

新闻内页-JS分页

精品推荐
分类导航