- //在文本框中光标当前的位置上插入字符串
- /**
- * 在文本框中光标当前的位置上插入字符串
- * tbid 为文本框的id,
- * str 为要插入的字符串
- */
- function InsertString(tbid, str){
- var tb = document.getElementById(tbid);
- tb.focus();
- if (document.all){
- var r = document.selection.createRange();
- document.selection.empty();
- r.text = str;
- r.collapse();
- r.select();
- }
- else{
- var newstart = tb.selectionStart+str.length;
- tb.value=tb.value.substr(0,tb.selectionStart)+str+tb.value.substring(tb.selectionEnd);
- tb.selectionStart = newstart;
- tb.selectionEnd = newstart;
- }
- }
- //获取文本框中选择的文本
- /**
- * 获取文本框中选择的文本
- * tbid 为要获取的文本框id
- */
- function GetSelection(tbid){
- var sel = '';
- if (document.all){
- var r = document.selection.createRange();
- document.selection.empty();
- sel = r.text;
- }
- else{
- var tb = document.getElementById(tbid);
- // tb.focus();
- var start = tb.selectionStart;
- var end = tb.selectionEnd;
- sel = tb.value.substring(start, end);
- }
- return sel;
- }
- //设置文本框中光标的位置
- /**
- * 设置文本框中光标的位置
- * tbid 为要获取的文本框id
- * pos 为要设置的位置
- */
- function setCaretPosition(tbid, pos){
- var ctrl=document.getElementById(tbid);
- if(ctrl.setSelectionRange){
- ctrl.focus();
- ctrl.setSelectionRange(pos,pos);
- }
- else if (ctrl.createTextRange) {
- var range = ctrl.createTextRange();
- range.collapse(true);
- range.moveEnd('character', pos);
- range.moveStart('character', pos);
- range.select();
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/130220148706.html
来源: http://www.codesnippet.cn/detail/130220148706.html