codebeautify.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * 代码格式化
  3. * @author 赵先烈
  4. */
  5. var CodeBeautify = (function(){
  6. var opts = {
  7. brace_style: "collapse",
  8. break_chained_methods: false,
  9. indent_char: " ",
  10. indent_scripts: "keep",
  11. indent_size: "4",
  12. keep_array_indentation: true,
  13. preserve_newlines: true,
  14. space_after_anon_function: true,
  15. space_before_conditional: true,
  16. unescape_strings: false,
  17. wrap_line_length: "120"
  18. };
  19. var codeType = 'Javascript';
  20. var bindEvent = function(){
  21. $('input[name="codeType"]').click(function(e){
  22. codeType = this.value;
  23. $('#codeTitle').html(this.value);
  24. });
  25. $('#btnFormat').click(function(e){
  26. if(codeType == 'Javascript') {
  27. var js = js_beautify($('#codeSource').val(),opts);
  28. js = js.replace(/>/g,'&gt;').replace(/</g,'&lt;');
  29. js = '<pre class="brush: js;toolbar:false;">' + js + '</pre>';
  30. $('#jfContent').html(js);
  31. }else if(codeType == 'CSS') {
  32. var css = css_beautify($('#codeSource').val());
  33. css = '<pre class="brush: css;toolbar:true;">' + css + '</pre>';
  34. $('#jfContent').html(css);
  35. }else if(codeType == 'HTML') {
  36. var html = html_beautify($('#codeSource').val());
  37. html = '<pre class="brush: html;toolbar:false;">' + html + '</pre>';
  38. $('#jfContent').html(html);
  39. }
  40. // 代码高亮
  41. SyntaxHighlighter.defaults['toolbar'] = false;
  42. SyntaxHighlighter.highlight();
  43. });
  44. };
  45. var init = function(){
  46. $(function(){
  47. //输入框聚焦
  48. jQuery("#codeSource").focus();
  49. bindEvent();
  50. })
  51. };
  52. return {
  53. init : init
  54. };
  55. })();
  56. CodeBeautify.init();