input-tab.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. function inputTab(selected, callfn) {
  2. var textbox = document.querySelector(selected),
  3. inputData,
  4. dataArr,
  5. keyCode;
  6. //事件对象
  7. var EventUtil = {
  8. //根据浏览器对象来使用不同的方法添加事件
  9. addHandler: function(element, type, handler) {
  10. if (element.addEventListener) {
  11. element.addEventListener(type, handler, true); //dom2级事件处理,在冒泡阶段捕获
  12. } else if (element.attachEvent) {
  13. element.attachEvent("on" + type, handler); //ie事件处理
  14. } else {
  15. element["on" + type] = handler; //dom0级事件处理
  16. }
  17. },
  18. //取消事件默认行为
  19. preventDefault: function(event) {
  20. if (event.preventDefault) {
  21. event.preventDefault();
  22. } else {
  23. event.returnValue = false;
  24. }
  25. },
  26. //取得event事件对象
  27. getEvent: function(event) {
  28. return event ? event: window.event;
  29. },
  30. //取得输入的字符编码
  31. getCharCode: function(event) {
  32. return event.keyCode;
  33. },
  34. //使tab键输出在textarea中
  35. inputTab: function(event) {
  36. keyCode = EventUtil.getCharCode(event);
  37. // EventUtil.preventDefault(event);
  38. if (keyCode == 9) {
  39. EventUtil.preventDefault(event);
  40. // textbox.value = textbox.value + '\t';
  41. insertText(textbox, '\t');
  42. }
  43. },
  44. };
  45. EventUtil.addHandler(textbox, "keydown",
  46. function() {
  47. EventUtil.inputTab(EventUtil.getEvent());
  48. });
  49. }
  50. function insertText(obj,str) {
  51. if (document.selection) {
  52. var sel = document.selection.createRange();
  53. sel.text = str;
  54. } else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
  55. var startPos = obj.selectionStart,
  56. endPos = obj.selectionEnd,
  57. cursorPos = startPos,
  58. tmpStr = obj.value;
  59. obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
  60. cursorPos += str.length;
  61. obj.selectionStart = obj.selectionEnd = cursorPos;
  62. } else {
  63. obj.value += str;
  64. }
  65. }