jquery.textarea.js 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. /*
  2. * 文本框使用tab按键,不会切换到其他的控件,而是相当于添加制表符。
  3. * 使用方法:
  4. * $("textarea").tabby();
  5. *
  6. */
  7. (function($) {
  8. // plugin definition
  9. $.fn.tabby = function(options) {
  10. //debug(this);
  11. // build main options before element iteration
  12. var opts = $.extend({}, $.fn.tabby.defaults, options);
  13. var pressed = $.fn.tabby.pressed;
  14. // iterate and reformat each matched element
  15. return this.each(function() {
  16. $this = $(this);
  17. // build element specific options
  18. var options = $.meta ? $.extend({}, opts, $this.data()) : opts;
  19. $this.bind('keydown',function (e) {
  20. var kc = $.fn.tabby.catch_kc(e);
  21. if (16 == kc) pressed.shft = true;
  22. /*
  23. because both CTRL+TAB and ALT+TAB default to an event (changing tab/window) that
  24. will prevent js from capturing the keyup event, we'll set a timer on releasing them.
  25. */
  26. if (17 == kc) {pressed.ctrl = true; setTimeout("$.fn.tabby.pressed.ctrl = false;",1000);}
  27. if (18 == kc) {pressed.alt = true; setTimeout("$.fn.tabby.pressed.alt = false;",1000);}
  28. if (9 == kc && !pressed.ctrl && !pressed.alt) {
  29. e.preventDefault; // does not work in O9.63 ??
  30. pressed.last = kc; setTimeout("$.fn.tabby.pressed.last = null;",0);
  31. process_keypress ($(e.target).get(0), pressed.shft, options);
  32. return false;
  33. }
  34. }).bind('keyup',function (e) {
  35. if (16 == $.fn.tabby.catch_kc(e)) pressed.shft = false;
  36. }).bind('blur',function (e) { // workaround for Opera -- http://www.webdeveloper.com/forum/showthread.php?p=806588
  37. if (9 == pressed.last) $(e.target).one('focus',function (e) {pressed.last = null;}).get(0).focus();
  38. });
  39. });
  40. };
  41. // define and expose any extra methods
  42. $.fn.tabby.catch_kc = function(e) { return e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which; };
  43. $.fn.tabby.pressed = {shft : false, ctrl : false, alt : false, last: null};
  44. // private function for debugging
  45. function debug($obj) {
  46. if (window.console && window.console.log)
  47. window.console.log('textarea count: ' + $obj.size());
  48. };
  49. function process_keypress (o,shft,options) {
  50. var scrollTo = o.scrollTop;
  51. //var tabString = String.fromCharCode(9);
  52. // gecko; o.setSelectionRange is only available when the text box has focus
  53. if (o.setSelectionRange) gecko_tab (o, shft, options);
  54. // ie; document.selection is always available
  55. else if (document.selection) ie_tab (o, shft, options);
  56. o.scrollTop = scrollTo;
  57. }
  58. // plugin defaults
  59. $.fn.tabby.defaults = {tabString : String.fromCharCode(9)};
  60. function gecko_tab (o, shft, options) {
  61. var ss = o.selectionStart;
  62. var es = o.selectionEnd;
  63. // when there's no selection and we're just working with the caret, we'll add/remove the tabs at the caret, providing more control
  64. if(ss == es) {
  65. // SHIFT+TAB
  66. if (shft) {
  67. // check to the left of the caret first
  68. if ("\t" == o.value.substring(ss-options.tabString.length, ss)) {
  69. o.value = o.value.substring(0, ss-options.tabString.length) + o.value.substring(ss); // put it back together omitting one character to the left
  70. o.focus();
  71. o.setSelectionRange(ss - options.tabString.length, ss - options.tabString.length);
  72. }
  73. // then check to the right of the caret
  74. else if ("\t" == o.value.substring(ss, ss + options.tabString.length)) {
  75. o.value = o.value.substring(0, ss) + o.value.substring(ss + options.tabString.length); // put it back together omitting one character to the right
  76. o.focus();
  77. o.setSelectionRange(ss,ss);
  78. }
  79. }
  80. // TAB
  81. else {
  82. o.value = o.value.substring(0, ss) + options.tabString + o.value.substring(ss);
  83. o.focus();
  84. o.setSelectionRange(ss + options.tabString.length, ss + options.tabString.length);
  85. }
  86. }
  87. // selections will always add/remove tabs from the start of the line
  88. else {
  89. // split the textarea up into lines and figure out which lines are included in the selection
  90. var lines = o.value.split("\n");
  91. var indices = new Array();
  92. var sl = 0; // start of the line
  93. var el = 0; // end of the line
  94. var sel = false;
  95. for (var i in lines) {
  96. el = sl + lines[i].length;
  97. indices.push({start: sl, end: el, selected: (sl <= ss && el > ss) || (el >= es && sl < es) || (sl > ss && el < es)});
  98. sl = el + 1;// for "\n"
  99. }
  100. // walk through the array of lines (indices) and add tabs where appropriate
  101. var modifier = 0;
  102. for (var i in indices) {
  103. if (indices[i].selected) {
  104. var pos = indices[i].start + modifier; // adjust for tabs already inserted/removed
  105. // SHIFT+TAB
  106. if (shft && options.tabString == o.value.substring(pos,pos+options.tabString.length)) { // only SHIFT+TAB if there's a tab at the start of the line
  107. o.value = o.value.substring(0,pos) + o.value.substring(pos + options.tabString.length); // omit the tabstring to the right
  108. modifier -= options.tabString.length;
  109. }
  110. // TAB
  111. else if (!shft) {
  112. o.value = o.value.substring(0,pos) + options.tabString + o.value.substring(pos); // insert the tabstring
  113. modifier += options.tabString.length;
  114. }
  115. }
  116. }
  117. o.focus();
  118. var ns = ss + ((modifier > 0) ? options.tabString.length : (modifier < 0) ? -options.tabString.length : 0);
  119. var ne = es + modifier;
  120. o.setSelectionRange(ns,ne);
  121. }
  122. }
  123. function ie_tab (o, shft, options) {
  124. var range = document.selection.createRange();
  125. if (o == range.parentElement()) {
  126. // when there's no selection and we're just working with the caret, we'll add/remove the tabs at the caret, providing more control
  127. if ('' == range.text) {
  128. // SHIFT+TAB
  129. if (shft) {
  130. var bookmark = range.getBookmark();
  131. //first try to the left by moving opening up our empty range to the left
  132. range.moveStart('character', -options.tabString.length);
  133. if (options.tabString == range.text) {
  134. range.text = '';
  135. } else {
  136. // if that didn't work then reset the range and try opening it to the right
  137. range.moveToBookmark(bookmark);
  138. range.moveEnd('character', options.tabString.length);
  139. if (options.tabString == range.text)
  140. range.text = '';
  141. }
  142. // move the pointer to the start of them empty range and select it
  143. range.collapse(true);
  144. range.select();
  145. }
  146. else {
  147. // very simple here. just insert the tab into the range and put the pointer at the end
  148. range.text = options.tabString;
  149. range.collapse(false);
  150. range.select();
  151. }
  152. }
  153. // selections will always add/remove tabs from the start of the line
  154. else {
  155. var selection_text = range.text;
  156. var selection_len = selection_text.length;
  157. var selection_arr = selection_text.split("\r\n");
  158. var before_range = document.body.createTextRange();
  159. before_range.moveToElementText(o);
  160. before_range.setEndPoint("EndToStart", range);
  161. var before_text = before_range.text;
  162. var before_arr = before_text.split("\r\n");
  163. var before_len = before_text.length; // - before_arr.length + 1;
  164. var after_range = document.body.createTextRange();
  165. after_range.moveToElementText(o);
  166. after_range.setEndPoint("StartToEnd", range);
  167. var after_text = after_range.text; // we can accurately calculate distance to the end because we're not worried about MSIE trimming a \r\n
  168. var end_range = document.body.createTextRange();
  169. end_range.moveToElementText(o);
  170. end_range.setEndPoint("StartToEnd", before_range);
  171. var end_text = end_range.text; // we can accurately calculate distance to the end because we're not worried about MSIE trimming a \r\n
  172. var check_html = $(o).html();
  173. $("#r3").text(before_len + " + " + selection_len + " + " + after_text.length + " = " + check_html.length);
  174. if((before_len + end_text.length) < check_html.length) {
  175. before_arr.push("");
  176. before_len += 2; // for the \r\n that was trimmed
  177. if (shft && options.tabString == selection_arr[0].substring(0,options.tabString.length))
  178. selection_arr[0] = selection_arr[0].substring(options.tabString.length);
  179. else if (!shft) selection_arr[0] = options.tabString + selection_arr[0];
  180. } else {
  181. if (shft && options.tabString == before_arr[before_arr.length-1].substring(0,options.tabString.length))
  182. before_arr[before_arr.length-1] = before_arr[before_arr.length-1].substring(options.tabString.length);
  183. else if (!shft) before_arr[before_arr.length-1] = options.tabString + before_arr[before_arr.length-1];
  184. }
  185. for (var i = 1; i < selection_arr.length; i++) {
  186. if (shft && options.tabString == selection_arr[i].substring(0,options.tabString.length))
  187. selection_arr[i] = selection_arr[i].substring(options.tabString.length);
  188. else if (!shft) selection_arr[i] = options.tabString + selection_arr[i];
  189. }
  190. if (1 == before_arr.length && 0 == before_len) {
  191. if (shft && options.tabString == selection_arr[0].substring(0,options.tabString.length))
  192. selection_arr[0] = selection_arr[0].substring(options.tabString.length);
  193. else if (!shft) selection_arr[0] = options.tabString + selection_arr[0];
  194. }
  195. if ((before_len + selection_len + after_text.length) < check_html.length) {
  196. selection_arr.push("");
  197. selection_len += 2; // for the \r\n that was trimmed
  198. }
  199. before_range.text = before_arr.join("\r\n");
  200. range.text = selection_arr.join("\r\n");
  201. var new_range = document.body.createTextRange();
  202. new_range.moveToElementText(o);
  203. if (0 < before_len) new_range.setEndPoint("StartToEnd", before_range);
  204. else new_range.setEndPoint("StartToStart", before_range);
  205. new_range.setEndPoint("EndToEnd", range);
  206. new_range.select();
  207. }
  208. }
  209. }
  210. // end of closure
  211. })(jQuery);