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

这篇博客介绍了如何使用JavaScript在TextArea中插入文本,并将光标移动到新插入文字的末尾。通过`insertText`函数实现文本插入,区分了IE和其他浏览器的处理方式。同时,`moveEnd`函数确保了光标的正确移动。这两个函数可以一起用于在用户输入时动态编辑TextArea内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. }  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值