markdown-editor.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. (function() {
  2. $.fn.markdown_editor = function() {
  3. return this.each(function() {
  4. var name = this.id;
  5. var this_form = this.form;
  6. $(this).replaceWith($('<div id="' + name + '-markdown-editor" class="markdown-editor"></div>')
  7. .append(
  8. $('<div id="' + name + '-markdown-editor-in" class="markdown-editor-in"></div>')
  9. .append($(this).clone())
  10. )
  11. .append(
  12. $('<div id="' + name + '-markdown-editor-out" class="markdown-editor-out"></div>')
  13. )
  14. );
  15. var needRerender = false;
  16. var update = function(e){
  17. var val = e.getValue();
  18. setOutput(val);
  19. needRerender = true;
  20. }
  21. var autoRerender = function() {
  22. if (needRerender) {
  23. needRerender = false;
  24. $('#' + name + '-markdown-editor-out').each(function() {
  25. sh_highlightDocument(this);
  26. MathJax.Hub.Queue(["Typeset", MathJax.Hub, this]);
  27. });
  28. }
  29. setTimeout(autoRerender, 500);
  30. }
  31. var setOutput = function(val){
  32. $('#' + name + '-markdown-editor-out').html(marked(val));
  33. }
  34. var codeeditor = CodeMirror.fromTextArea($('#' + name)[0], {
  35. mode: 'gfm',
  36. lineNumbers: true,
  37. matchBrackets: true,
  38. lineWrapping: true,
  39. styleActiveLine: true,
  40. theme: 'default'
  41. });
  42. codeeditor.on('change', update);
  43. if (this_form) {
  44. var changed = false;
  45. codeeditor.on('change', function() {
  46. before_window_unload_message = '您所编辑的内容尚未保存';
  47. changed = true;
  48. });
  49. $(this_form).submit(function() {
  50. if (changed) {
  51. before_window_unload_message = null;
  52. }
  53. changed = false;
  54. });
  55. }
  56. update(codeeditor);
  57. autoRerender();
  58. });
  59. };
  60. })()