JS在TextArea光标位置插入文字+移动光标到文字末尾

来源:互联网 发布:淘宝如何修改身份认证 编辑:程序博客网 时间:2024/05/16 09:54
Js代码  收藏代码
  1. function insertText(obj,str) {  
  2.   
  3.     if (document.selection) {  
  4.   
  5.         var sel = document.selection.createRange();  
  6.   
  7.         sel.text = str;  
  8.   
  9.     } else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {  
  10.   
  11.         var startPos = obj.selectionStart,  
  12.   
  13.             endPos = obj.selectionEnd,  
  14.   
  15.             cursorPos = startPos,  
  16.   
  17.             tmpStr = obj.value;  
  18.   
  19.         obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);  
  20.   
  21.         cursorPos += str.length;  
  22.   
  23.         obj.selectionStart = obj.selectionEnd = cursorPos;  
  24.   
  25.     } else {  
  26.   
  27.         obj.value += str;  
  28.   
  29.     }  
  30.   
  31. }  
  32.   
  33. function moveEnd(obj){  
  34.   
  35.     obj.focus();  
  36.   
  37.     var len = obj.value.length;  
  38.   
  39.     if (document.selection) {  
  40.   
  41.         var sel = obj.createTextRange();  
  42.   
  43.         sel.moveStart('character',len);  
  44.   
  45.         sel.collapse();  
  46.   
  47.         sel.select();  
  48.   
  49.     } else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') {  
  50.   
  51.         obj.selectionStart = obj.selectionEnd = len;  
  52.   
  53.     }  
  54.   
  55.   
  56. }  

 

0 0
原创粉丝点击