jquery.caretInsert.js 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // JavaScript Document
  2. jQuery.extend({
  3. /**
  4. * 清除当前选择内容
  5. */
  6. unselectContents: function(){
  7. if(window.getSelection)
  8. window.getSelection().removeAllRanges();
  9. else if(document.selection)
  10. document.selection.empty();
  11. }
  12. });
  13. jQuery.fn.extend({
  14. /**
  15. * 选中内容
  16. */
  17. selectContents: function(){
  18. $(this).each(function(i){
  19. var node = this;
  20. var selection, range, doc, win;
  21. if ((doc = node.ownerDocument) &&
  22. (win = doc.defaultView) &&
  23. typeof win.getSelection != 'undefined' &&
  24. typeof doc.createRange != 'undefined' &&
  25. (selection = window.getSelection()) &&
  26. typeof selection.removeAllRanges != 'undefined')
  27. {
  28. range = doc.createRange();
  29. range.selectNode(node);
  30. if(i == 0){
  31. selection.removeAllRanges();
  32. }
  33. selection.addRange(range);
  34. }
  35. else if (document.body &&
  36. typeof document.body.createTextRange != 'undefined' &&
  37. (range = document.body.createTextRange()))
  38. {
  39. range.moveToElementText(node);
  40. range.select();
  41. }
  42. });
  43. },
  44. /**
  45. * 初始化对象以支持光标处插入内容
  46. */
  47. setCaret: function(){
  48. if(!$.support.msie) return;
  49. var initSetCaret = function(){
  50. var textObj = $(this).get(0);
  51. textObj.caretPos = document.selection.createRange().duplicate();
  52. };
  53. $(this)
  54. .click(initSetCaret)
  55. .select(initSetCaret)
  56. .keyup(initSetCaret);
  57. },
  58. /**
  59. * 在当前对象光标处插入指定的内容
  60. */
  61. insertAtCaret: function(textFeildValue){
  62. var textObj = $(this).get(0);
  63. if(document.all && textObj.createTextRange && textObj.caretPos){
  64. var caretPos=textObj.caretPos;
  65. caretPos.text = caretPos.text.charAt(caretPos.text.length-1) == '' ?
  66. textFeildValue+'' : textFeildValue;
  67. }
  68. else if(textObj.setSelectionRange){
  69. var rangeStart=textObj.selectionStart;
  70. var rangeEnd=textObj.selectionEnd;
  71. var tempStr1=textObj.value.substring(0,rangeStart);
  72. var tempStr2=textObj.value.substring(rangeEnd);
  73. textObj.value=tempStr1+textFeildValue+tempStr2;
  74. textObj.focus();
  75. var len=textFeildValue.length;
  76. textObj.setSelectionRange(rangeStart+len,rangeStart+len);
  77. textObj.blur();
  78. }
  79. else {
  80. textObj.value+=textFeildValue;
  81. }
  82. }
  83. });