首页 > 网站 > WEB开发 > 正文

javascript 获取光标所选中的内容并插入到另一个文本框中(兼容ie和ff)

2024-04-27 14:22:59
字体:
来源:转载
供稿:网友

javascript 获取光标所选中的内容并插入到另一个文本框中(兼容ie和ff)

项目中正好用到 做下笔记方便以后查找

ie获取光标的位置使用document.selection.createRange()

火狐下使用document.getElementById(id).selectionStart 和document.getElementById(id).selectionEnd

假设我们要获得id为txt的Textarea元素里面光标所选择的内容

首先创建一个获得光标所选内容的函数(参数:火狐下需要Dom元素 select_field=document.getElementById(txt))

var Word="";

function getFieldSelection(select_field) { if (document.selection) {//这里判断是否是ie浏览器 var sel = document.selection.createRange();//document.selection.createRange() 根据当前文字选择返回 TextRange 对象,或根据控件选择返回 ControlRange 对象。配合 execCommand,在 HTML 编辑器中很有用,比如:文字加粗、斜体、复制、粘贴、创建超链接等 if (sel.text.length > 0) {//document.selection.createRange().text就是获取文本域里选中的一段文字,大于0判断是否有选中 word = sel.text; } } else if (select_field.selectionStart || select_field.selectionStart == '0') {//这里判断浏览器是否是火狐 var startP = select_field.selectionStart;//获得光标选中内容的开始位置 var endP = select_field.selectionEnd;//获得光标选中内容的结束位置 if (startP != endP) {//判断是否选中了 如果位置一样 说明没有选中 word = select_field.value.substring(startP, endP);//用substring截取选中的内容 } } }

上述就可以拿到选中的内容了

接下来我们把选中的内容插入到另一个文本框中

$("#txtMoudler").click(function () { var select_field = $(this)[0]; var content =word; if (content != "") { if (document.selection) {//ie6 var sel = document.selection.createRange(); //获取ie光标位置 if (document.selection.type != "None") { sel.text = content; sel.select();//光标设置到添加内容的后面 } } else if (select_field.selectionStart || select_field.selectionStart == '0') {//这里判断浏览器是否是火狐 var start = select_field.selectionStart; //获取光标焦点前坐标 var end = select_field.selectionEnd; //获取光标焦点后坐标

//重新写入文本框中的内容 select_field.value = select_field.value.substring(0, start) + content + select_field.value.substring(end, select_field.value.length); var lengths = select_field.value.substring(0, Number(start)).length + content.length; select_field.setSelectionRange(lengths, lengths);//光标设置到添加内容的后面 $(this).focus(); } } });


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表