歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> jQuery或者JavaScript實現在textarea光標處插入文本

jQuery或者JavaScript實現在textarea光標處插入文本

日期:2017/3/1 10:29:14   编辑:Linux編程

1.Jquery函數實現:

  1. $(function() {
  2. /* 在textarea處插入文本--Start */
  3. (function($) {
  4. $.fn
  5. .extend({
  6. insertContent : function(myValue, t) {
  7. var $t = $(this)[0];
  8. if (document.selection) { // ie
  9. this.focus();
  10. var sel = document.selection.createRange();
  11. sel.text = myValue;
  12. this.focus();
  13. sel.moveStart('character', -l);
  14. var wee = sel.text.length;
  15. if (arguments.length == 2) {
  16. var l = $t.value.length;
  17. sel.moveEnd("character", wee + t);
  18. t <= 0 ? sel.moveStart("character", wee - 2 * t
  19. - myValue.length) : sel.moveStart(
  20. "character", wee - t - myValue.length);
  21. sel.select();
  22. }
  23. } else if ($t.selectionStart
  24. || $t.selectionStart == '0') {
  25. var startPos = $t.selectionStart;
  26. var endPos = $t.selectionEnd;
  27. var scrollTop = $t.scrollTop;
  28. $t.value = $t.value.substring(0, startPos)
  29. + myValue
  30. + $t.value.substring(endPos,
  31. $t.value.length);
  32. this.focus();
  33. $t.selectionStart = startPos + myValue.length;
  34. $t.selectionEnd = startPos + myValue.length;
  35. $t.scrollTop = scrollTop;
  36. if (arguments.length == 2) {
  37. $t.setSelectionRange(startPos - t,
  38. $t.selectionEnd + t);
  39. this.focus();
  40. }
  41. } else {
  42. this.value += myValue;
  43. this.focus();
  44. }
  45. }
  46. })
  47. })(jQuery);
  48. /* 在textarea處插入文本--Ending */
  49. });
調用方法:

$(文本域選擇器).insertContent("插入的內容");
//$(文本域選擇器).insertContent("插入的內容",數值); //根據數值選中插入文本內容兩邊的邊界, 數值: 0是表示插入文字全部選擇,-1表示插入文字兩邊各少選中一個字符。


2.JavaScript實現:

  1. function insertText(obj,str) {
  2. if (document.selection) {
  3. var sel = document.selection.createRange();
  4. sel.text = str;
  5. } else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
  6. var startPos = obj.selectionStart,
  7. endPos = obj.selectionEnd,
  8. cursorPos = startPos,
  9. tmpStr = obj.value;
  10. obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
  11. cursorPos += str.length;
  12. obj.selectionStart = obj.selectionEnd = cursorPos;
  13. } else {
  14. obj.value += str;
  15. }
  16. }
  17. function moveEnd(obj){
  18. obj.focus();
  19. var len = obj.value.length;
  20. if (document.selection) {
  21. var sel = obj.createTextRange();
  22. sel.moveStart('character',len);
  23. sel.collapse();
  24. sel.select();
  25. } else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') {
  26. obj.selectionStart = obj.selectionEnd = len;
  27. }
  28. }
Copyright © Linux教程網 All Rights Reserved