吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2585|回复: 3
收起左侧

[Java 原创] JavaScript脚本预览本地markdown图书(支持SUMMARY书目TOC和章节TOC)

[复制链接]
763221847 发表于 2018-8-3 18:02
本帖最后由 763221847 于 2018-8-3 19:01 编辑

123.png

使用需求:

  • 浏览器需要支持以下任一插件
    • Greasemonkey
    • Tampermonkey
    • Violentmonkey
      新建一个脚本文件然后把代码粘贴进去就可以生效了

[JavaScript] 纯文本查看 复制代码
// ==UserScript==
// @id             763221847@qq.com.com
// @namespace      https://gitee.com/isteng/
// @name           markdown_preview
// @name:zh-CN     SUMMARY
// @version        0.12
// @description    预览本地Markdown文件
// @author         Teng
// @match          file:///*/*.md*
// @match          file:///*/*.MD*
// @exclude        file:///*/SUMMARY.MD*
// @exclude        file:///*/SUMMARY.md*
// @grant          None
// ==/UserScript==
// console.log(tochtml)  // 输出到控制台

// -------------------- markdown转HTML代码 --------------------
!function(e){"use strict";var t={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:f,hr:/^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *(?:#+ *)?(?:\n+|$)/,nptable:f,blockquote:/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:"^ {0,3}(?:<(script|pre|style)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?\\?>\\n*|<![A-Z][\\s\\S]*?>\\n*|<!\\[CDATA\\[[\\s\\S]*?\\]\\]>\\n*|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:\\n{2,}|$)|<(?!script|pre|style)([a-z][\\w-]*)(?:attribute)*? */?>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$)|</(?!script|pre|style)[a-z][\\w-]*\\s*>(?=\\h*\\n)[\\s\\S]*?(?:\\n{2,}|$))",def:/^ {0,3}\[(label)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)(title))? *(?:\n+|$)/,table:f,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,paragraph:/^([^\n]+(?:\n(?!hr|heading|lheading| {0,3}>|<\/?(?:tag)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/,text:/^[^\n]+/};function n(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||k.defaults,this.rules=t.normal,this.options.pedantic?this.rules=t.pedantic:this.options.gfm&&(this.options.tables?this.rules=t.tables:this.rules=t.gfm)}t._label=/(?!\s*\])(?:\\[\[\]]|[^\[\]])+/,t._title=/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/,t.def=p(t.def).replace("label",t._label).replace("title",t._title).getRegex(),t.bullet=/(?:[*+-]|\d+\.)/,t.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/,t.item=p(t.item,"gm").replace(/bull/g,t.bullet).getRegex(),t.list=p(t.list).replace(/bull/g,t.bullet).replace("hr","\\n+(?=\\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$))").replace("def","\\n+(?="+t.def.source+")").getRegex(),t._tag="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",t._comment=/<!--(?!-?>)[\s\S]*?-->/,t.html=p(t.html,"i").replace("comment",t._comment).replace("tag",t._tag).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),t.paragraph=p(t.paragraph).replace("hr",t.hr).replace("heading",t.heading).replace("lheading",t.lheading).replace("tag",t._tag).getRegex(),t.blockquote=p(t.blockquote).replace("paragraph",t.paragraph).getRegex(),t.normal=d({},t),t.gfm=d({},t.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\n? *\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/}),t.gfm.paragraph=p(t.paragraph).replace("(?!","(?!"+t.gfm.fences.source.replace("\\1","\\2")+"|"+t.list.source.replace("\\1","\\3")+"|").getRegex(),t.tables=d({},t.gfm,{nptable:/^ *([^|\n ].*\|.*)\n *([-:]+ *\|[-| :]*)(?:\n((?:.*[^>\n ].*(?:\n|$))*)\n*|$)/,table:/^ *\|(.+)\n *\|?( *[-:]+[-| :]*)(?:\n((?: *[^>\n ].*(?:\n|$))*)\n*|$)/}),t.pedantic=d({},t.normal,{html:p("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",t._comment).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/}),n.rules=t,n.lex=function(e,t){return new n(t).lex(e)},n.prototype.lex=function(e){return e=e.replace(/\r\n|\r/g,"\n").replace(/\t/g,"    ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n"),this.token(e,!0)},n.prototype.token=function(e,n){var r,s,i,l,o,a,h,p,u,c,g,f,d,k,x,y;for(e=e.replace(/^ +$/gm,"");e;)if((i=this.rules.newline.exec(e))&&(e=e.substring(i[0].length),i[0].length>1&&this.tokens.push({type:"space"})),i=this.rules.code.exec(e))e=e.substring(i[0].length),i=i[0].replace(/^ {4}/gm,""),this.tokens.push({type:"code",text:this.options.pedantic?i:m(i,"\n")});else if(i=this.rules.fences.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"code",lang:i[2],text:i[3]||""});else if(i=this.rules.heading.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"heading",depth:i[1].length,text:i[2]});else if(n&&(i=this.rules.nptable.exec(e))&&(a={type:"table",header:b(i[1].replace(/^ *| *\| *$/g,"")),align:i[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:i[3]?i[3].replace(/\n$/,"").split("\n"):[]}).header.length===a.align.length){for(e=e.substring(i[0].length),g=0;g<a.align.length;g++)/^ *-+: *$/.test(a.align[g])?a.align[g]="right":/^ *:-+: *$/.test(a.align[g])?a.align[g]="center":/^ *:-+ *$/.test(a.align[g])?a.align[g]="left":a.align[g]=null;for(g=0;g<a.cells.length;g++)a.cells[g]=b(a.cells[g],a.header.length);this.tokens.push(a)}else if(i=this.rules.hr.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"hr"});else if(i=this.rules.blockquote.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"blockquote_start"}),i=i[0].replace(/^ *> ?/gm,""),this.token(i,n),this.tokens.push({type:"blockquote_end"});else if(i=this.rules.list.exec(e)){for(e=e.substring(i[0].length),h={type:"list_start",ordered:k=(l=i[2]).length>1,start:k?+l:"",loose:!1},this.tokens.push(h),p=[],r=!1,d=(i=i[0].match(this.rules.item)).length,g=0;g<d;g++)c=(a=i[g]).length,~(a=a.replace(/^ *([*+-]|\d+\.) +/,"")).indexOf("\n ")&&(c-=a.length,a=this.options.pedantic?a.replace(/^ {1,4}/gm,""):a.replace(new RegExp("^ {1,"+c+"}","gm"),"")),this.options.smartLists&&g!==d-1&&(l===(o=t.bullet.exec(i[g+1])[0])||l.length>1&&o.length>1||(e=i.slice(g+1).join("\n")+e,g=d-1)),s=r||/\n\n(?!\s*$)/.test(a),g!==d-1&&(r="\n"===a.charAt(a.length-1),s||(s=r)),s&&(h.loose=!0),y=void 0,(x=/^\[[ xX]\] /.test(a))&&(y=" "!==a[1],a=a.replace(/^\[[ xX]\] +/,"")),u={type:"list_item_start",task:x,checked:y,loose:s},p.push(u),this.tokens.push(u),this.token(a,!1),this.tokens.push({type:"list_item_end"});if(h.loose)for(d=p.length,g=0;g<d;g++)p[g].loose=!0;this.tokens.push({type:"list_end"})}else if(i=this.rules.html.exec(e))e=e.substring(i[0].length),this.tokens.push({type:this.options.sanitize?"paragraph":"html",pre:!this.options.sanitizer&&("pre"===i[1]||"script"===i[1]||"style"===i[1]),text:i[0]});else if(n&&(i=this.rules.def.exec(e)))e=e.substring(i[0].length),i[3]&&(i[3]=i[3].substring(1,i[3].length-1)),f=i[1].toLowerCase().replace(/\s+/g," "),this.tokens.links[f]||(this.tokens.links[f]={href:i[2],title:i[3]});else if(n&&(i=this.rules.table.exec(e))&&(a={type:"table",header:b(i[1].replace(/^ *| *\| *$/g,"")),align:i[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:i[3]?i[3].replace(/(?: *\| *)?\n$/,"").split("\n"):[]}).header.length===a.align.length){for(e=e.substring(i[0].length),g=0;g<a.align.length;g++)/^ *-+: *$/.test(a.align[g])?a.align[g]="right":/^ *:-+: *$/.test(a.align[g])?a.align[g]="center":/^ *:-+ *$/.test(a.align[g])?a.align[g]="left":a.align[g]=null;for(g=0;g<a.cells.length;g++)a.cells[g]=b(a.cells[g].replace(/^ *\| *| *\| *$/g,""),a.header.length);this.tokens.push(a)}else if(i=this.rules.lheading.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"heading",depth:"="===i[2]?1:2,text:i[1]});else if(n&&(i=this.rules.paragraph.exec(e)))e=e.substring(i[0].length),this.tokens.push({type:"paragraph",text:"\n"===i[1].charAt(i[1].length-1)?i[1].slice(0,-1):i[1]});else if(i=this.rules.text.exec(e))e=e.substring(i[0].length),this.tokens.push({type:"text",text:i[0]});else if(e)throw new Error("Infinite loop on byte: "+e.charCodeAt(0));return this.tokens};var r={escape:/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,autolink:/^<(scheme:[^\s\x00-\x1f<>]*|email)>/,url:f,tag:"^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>",link:/^!?\[(label)\]\(href(?:\s+(title))?\s*\)/,reflink:/^!?\[(label)\]\[(?!\s*\])((?:\\[\[\]]?|[^\[\]\\])+)\]/,nolink:/^!?\[(?!\s*\])((?:\[[^\[\]]*\]|\\[\[\]]|[^\[\]])*)\](?:\[\])?/,strong:/^__([^\s][\s\S]*?[^\s])__(?!_)|^\*\*([^\s][\s\S]*?[^\s])\*\*(?!\*)|^__([^\s])__(?!_)|^\*\*([^\s])\*\*(?!\*)/,em:/^_([^\s][\s\S]*?[^\s_])_(?!_)|^_([^\s_][\s\S]*?[^\s])_(?!_)|^\*([^\s][\s\S]*?[^\s*])\*(?!\*)|^\*([^\s*][\s\S]*?[^\s])\*(?!\*)|^_([^\s_])_(?!_)|^\*([^\s*])\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`]?)\s*\1(?!`)/,br:/^( {2,}|\\)\n(?!\s*$)/,del:f,text:/^[\s\S]+?(?=[\\<!\[`*]|\b_| {2,}\n|$)/};function s(e,t){if(this.options=t||k.defaults,this.links=e,this.rules=r.normal,this.renderer=this.options.renderer||new i,this.renderer.options=this.options,!this.links)throw new Error("Tokens array requires a `links` property.");this.options.pedantic?this.rules=r.pedantic:this.options.gfm&&(this.options.breaks?this.rules=r.breaks:this.rules=r.gfm)}function i(e){this.options=e||k.defaults}function l(){}function o(e){this.tokens=[],this.token=null,this.options=e||k.defaults,this.options.renderer=this.options.renderer||new i,this.renderer=this.options.renderer,this.renderer.options=this.options}function a(e,t){return e.replace(t?/&/g:/&(?!#?\w+;)/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function h(e){return e.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi,function(e,t){return"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""})}function p(e,t){return e=e.source||e,t=t||"",{replace:function(t,n){return n=(n=n.source||n).replace(/(^|[^\[])\^/g,"$1"),e=e.replace(t,n),this},getRegex:function(){return new RegExp(e,t)}}}function u(e,t){return c[" "+e]||(/^[^:]+:\/*[^/]*$/.test(e)?c[" "+e]=e+"/":c[" "+e]=m(e,"/",!0)),e=c[" "+e],"//"===t.slice(0,2)?e.replace(/:[\s\S]*/,":")+t:"/"===t.charAt(0)?e.replace(/(:\/*[^/]*)[\s\S]*/,"$1")+t:e+t}r._escapes=/\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/g,r._scheme=/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/,r._email=/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/,r.autolink=p(r.autolink).replace("scheme",r._scheme).replace("email",r._email).getRegex(),r._attribute=/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/,r.tag=p(r.tag).replace("comment",t._comment).replace("attribute",r._attribute).getRegex(),r._label=/(?:\[[^\[\]]*\]|\\[\[\]]?|`[^`]*`|[^\[\]\\])*?/,r._href=/\s*(<(?:\\[<>]?|[^\s<>\\])*>|(?:\\[()]?|\([^\s\x00-\x1f\\]*\)|[^\s\x00-\x1f()\\])*?)/,r._title=/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/,r.link=p(r.link).replace("label",r._label).replace("href",r._href).replace("title",r._title).getRegex(),r.reflink=p(r.reflink).replace("label",r._label).getRegex(),r.normal=d({},r),r.pedantic=d({},r.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/,link:p(/^!?\[(label)\]\((.*?)\)/).replace("label",r._label).getRegex(),reflink:p(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",r._label).getRegex()}),r.gfm=d({},r.normal,{escape:p(r.escape).replace("])","~|])").getRegex(),url:p(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("email",r._email).getRegex(),_backpedal:/(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/,del:/^~+(?=\S)([\s\S]*?\S)~+/,text:p(r.text).replace("]|","~]|").replace("|","|https?://|ftp://|www\\.|[a-zA-Z0-9.!#$%&'*+/=?^_`{\\|}~-]+@|").getRegex()}),r.breaks=d({},r.gfm,{br:p(r.br).replace("{2,}","*").getRegex(),text:p(r.gfm.text).replace("{2,}","*").getRegex()}),s.rules=r,s.output=function(e,t,n){return new s(t,n).output(e)},s.prototype.output=function(e){for(var t,n,r,i,l,o,h="";e;)if(l=this.rules.escape.exec(e))e=e.substring(l[0].length),h+=l[1];else if(l=this.rules.autolink.exec(e))e=e.substring(l[0].length),r="@"===l[2]?"mailto:"+(n=a(this.mangle(l[1]))):n=a(l[1]),h+=this.renderer.link(r,null,n);else if(this.inLink||!(l=this.rules.url.exec(e))){if(l=this.rules.tag.exec(e))!this.inLink&&/^<a /i.test(l[0])?this.inLink=!0:this.inLink&&/^<\/a>/i.test(l[0])&&(this.inLink=!1),e=e.substring(l[0].length),h+=this.options.sanitize?this.options.sanitizer?this.options.sanitizer(l[0]):a(l[0]):l[0];else if(l=this.rules.link.exec(e))e=e.substring(l[0].length),this.inLink=!0,r=l[2],this.options.pedantic?(t=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(r))?(r=t[1],i=t[3]):i="":i=l[3]?l[3].slice(1,-1):"",r=r.trim().replace(/^<([\s\S]*)>$/,"$1"),h+=this.outputLink(l,{href:s.escapes(r),title:s.escapes(i)}),this.inLink=!1;else if((l=this.rules.reflink.exec(e))||(l=this.rules.nolink.exec(e))){if(e=e.substring(l[0].length),t=(l[2]||l[1]).replace(/\s+/g," "),!(t=this.links[t.toLowerCase()])||!t.href){h+=l[0].charAt(0),e=l[0].substring(1)+e;continue}this.inLink=!0,h+=this.outputLink(l,t),this.inLink=!1}else if(l=this.rules.strong.exec(e))e=e.substring(l[0].length),h+=this.renderer.strong(this.output(l[4]||l[3]||l[2]||l[1]));else if(l=this.rules.em.exec(e))e=e.substring(l[0].length),h+=this.renderer.em(this.output(l[6]||l[5]||l[4]||l[3]||l[2]||l[1]));else if(l=this.rules.code.exec(e))e=e.substring(l[0].length),h+=this.renderer.codespan(a(l[2].trim(),!0));else if(l=this.rules.br.exec(e))e=e.substring(l[0].length),h+=this.renderer.br();else if(l=this.rules.del.exec(e))e=e.substring(l[0].length),h+=this.renderer.del(this.output(l[1]));else if(l=this.rules.text.exec(e))e=e.substring(l[0].length),h+=this.renderer.text(a(this.smartypants(l[0])));else if(e)throw new Error("Infinite loop on byte: "+e.charCodeAt(0))}else{do{o=l[0],l[0]=this.rules._backpedal.exec(l[0])[0]}while(o!==l[0]);e=e.substring(l[0].length),"@"===l[2]?r="mailto:"+(n=a(l[0])):(n=a(l[0]),r="www."===l[1]?"http://"+n:n),h+=this.renderer.link(r,null,n)}return h},s.escapes=function(e){return e?e.replace(s.rules._escapes,"$1"):e},s.prototype.outputLink=function(e,t){var n=t.href,r=t.title?a(t.title):null;return"!"!==e[0].charAt(0)?this.renderer.link(n,r,this.output(e[1])):this.renderer.image(n,r,a(e[1]))},s.prototype.smartypants=function(e){return this.options.smartypants?e.replace(/---/g,"—").replace(/--/g,"–").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1‘").replace(/'/g,"’").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1“").replace(/"/g,"”").replace(/\.{3}/g,"…"):e},s.prototype.mangle=function(e){if(!this.options.mangle)return e;for(var t,n="",r=e.length,s=0;s<r;s++)t=e.charCodeAt(s),Math.random()>.5&&(t="x"+t.toString(16)),n+="&#"+t+";";return n},i.prototype.code=function(e,t,n){if(this.options.highlight){var r=this.options.highlight(e,t);null!=r&&r!==e&&(n=!0,e=r)}return t?'<pre><code class="'+this.options.langPrefix+a(t,!0)+'">'+(n?e:a(e,!0))+"</code></pre>\n":"<pre><code>"+(n?e:a(e,!0))+"</code></pre>"},i.prototype.blockquote=function(e){return"<blockquote>\n"+e+"</blockquote>\n"},i.prototype.html=function(e){return e},i.prototype.heading=function(e,t,n){return this.options.headerIds?"<h"+t+' id="'+this.options.headerPrefix+n.toLowerCase().replace(/[^\w]+/g,"-")+'">'+e+"</h"+t+">\n":"<h"+t+">"+e+"</h"+t+">\n"},i.prototype.hr=function(){return this.options.xhtml?"<hr/>\n":"<hr>\n"},i.prototype.list=function(e,t,n){var r=t?"ol":"ul";return"<"+r+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"</"+r+">\n"},i.prototype.listitem=function(e){return"<li>"+e+"</li>\n"},i.prototype.checkbox=function(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"'+(this.options.xhtml?" /":"")+"> "},i.prototype.paragraph=function(e){return"<p>"+e+"</p>\n"},i.prototype.table=function(e,t){return t&&(t="<tbody>"+t+"</tbody>"),"<table>\n<thead>\n"+e+"</thead>\n"+t+"</table>\n"},i.prototype.tablerow=function(e){return"<tr>\n"+e+"</tr>\n"},i.prototype.tablecell=function(e,t){var n=t.header?"th":"td";return(t.align?"<"+n+' align="'+t.align+'">':"<"+n+">")+e+"</"+n+">\n"},i.prototype.strong=function(e){return"<strong>"+e+"</strong>"},i.prototype.em=function(e){return"<em>"+e+"</em>"},i.prototype.codespan=function(e){return"<code>"+e+"</code>"},i.prototype.br=function(){return this.options.xhtml?"<br/>":"<br>"},i.prototype.del=function(e){return"<del>"+e+"</del>"},i.prototype.link=function(e,t,n){if(this.options.sanitize){try{var r=decodeURIComponent(h(e)).replace(/[^\w:]/g,"").toLowerCase()}catch(e){return n}if(0===r.indexOf("javascript:")||0===r.indexOf("vbscript:")||0===r.indexOf("data:"))return n}this.options.baseUrl&&!g.test(e)&&(e=u(this.options.baseUrl,e));try{e=encodeURI(e).replace(/%25/g,"%")}catch(e){return n}var s='<a href="'+a(e)+'"';return t&&(s+=' title="'+t+'"'),s+=">"+n+"</a>"},i.prototype.image=function(e,t,n){this.options.baseUrl&&!g.test(e)&&(e=u(this.options.baseUrl,e));var r='<img src="'+e+'" alt="'+n+'"';return t&&(r+=' title="'+t+'"'),r+=this.options.xhtml?"/>":">"},i.prototype.text=function(e){return e},l.prototype.strong=l.prototype.em=l.prototype.codespan=l.prototype.del=l.prototype.text=function(e){return e},l.prototype.link=l.prototype.image=function(e,t,n){return""+n},l.prototype.br=function(){return""},o.parse=function(e,t){return new o(t).parse(e)},o.prototype.parse=function(e){this.inline=new s(e.links,this.options),this.inlineText=new s(e.links,d({},this.options,{renderer:new l})),this.tokens=e.reverse();for(var t="";this.next();)t+=this.tok();return t},o.prototype.next=function(){return this.token=this.tokens.pop()},o.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0},o.prototype.parseText=function(){for(var e=this.token.text;"text"===this.peek().type;)e+="\n"+this.next().text;return this.inline.output(e)},o.prototype.tok=function(){switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,h(this.inlineText.output(this.token.text)));case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":var e,t,n,r,s="",i="";for(n="",e=0;e<this.token.header.length;e++)n+=this.renderer.tablecell(this.inline.output(this.token.header[e]),{header:!0,align:this.token.align[e]});for(s+=this.renderer.tablerow(n),e=0;e<this.token.cells.length;e++){for(t=this.token.cells[e],n="",r=0;r<t.length;r++)n+=this.renderer.tablecell(this.inline.output(t[r]),{header:!1,align:this.token.align[r]});i+=this.renderer.tablerow(n)}return this.renderer.table(s,i);case"blockquote_start":for(i="";"blockquote_end"!==this.next().type;)i+=this.tok();return this.renderer.blockquote(i);case"list_start":i="";for(var l=this.token.ordered,o=this.token.start;"list_end"!==this.next().type;)i+=this.tok();return this.renderer.list(i,l,o);case"list_item_start":i="";var a=this.token.loose;for(this.token.task&&(i+=this.renderer.checkbox(this.token.checked));"list_item_end"!==this.next().type;)i+=a||"text"!==this.token.type?this.tok():this.parseText();return this.renderer.listitem(i);case"html":return this.renderer.html(this.token.text);case"paragraph":return this.renderer.paragraph(this.inline.output(this.token.text));case"text":return this.renderer.paragraph(this.parseText())}};var c={},g=/^$|^[a-z][a-z0-9+.-]*:|^[?#]/i;function f(){}function d(e){for(var t,n,r=1;r<arguments.length;r++)for(n in t=arguments[r])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}function b(e,t){var n=e.replace(/\|/g,function(e,t,n){for(var r=!1,s=t;--s>=0&&"\\"===n[s];)r=!r;return r?"|":" |"}).split(/ \|/),r=0;if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;r<n.length;r++)n[r]=n[r].trim().replace(/\\\|/g,"|");return n}function m(e,t,n){if(0===e.length)return"";for(var r=0;r<e.length;){var s=e.charAt(e.length-r-1);if(s!==t||n){if(s===t||!n)break;r++}else r++}return e.substr(0,e.length-r)}function k(e,t,r){if(null==e)throw new Error("marked(): input parameter is undefined or null");if("string"!=typeof e)throw new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected");if(r||"function"==typeof t){r||(r=t,t=null);var s,i,l=(t=d({},k.defaults,t||{})).highlight,h=0;try{s=n.lex(e,t)}catch(e){return r(e)}i=s.length;var p=function(e){if(e)return t.highlight=l,r(e);var n;try{n=o.parse(s,t)}catch(t){e=t}return t.highlight=l,e?r(e):r(null,n)};if(!l||l.length<3)return p();if(delete t.highlight,!i)return p();for(;h<s.length;h++)!function(e){"code"!==e.type?--i||p():l(e.text,e.lang,function(t,n){return t?p(t):null==n||n===e.text?--i||p():(e.text=n,e.escaped=!0,void(--i||p()))})}(s[h])}else try{return t&&(t=d({},k.defaults,t)),o.parse(n.lex(e,t),t)}catch(e){if(e.message+="\nPlease report this to https://github.com/markedjs/marked.",(t||k.defaults).silent)return"<p>An error occurred:</p><pre>"+a(e.message+"",!0)+"</pre>";throw e}}f.exec=f,k.options=k.setOptions=function(e){return d(k.defaults,e),k},k.getDefaults=function(){return{baseUrl:null,breaks:!1,gfm:!0,headerIds:!0,headerPrefix:"",highlight:null,langPrefix:"language-",mangle:!0,pedantic:!1,renderer:new i,sanitize:!1,sanitizer:null,silent:!1,smartLists:!1,smartypants:!1,tables:!0,xhtml:!1}},k.defaults=k.getDefaults(),k.Parser=o,k.parser=o.parse,k.Renderer=i,k.TextRenderer=l,k.Lexer=n,k.lexer=n.lex,k.InlineLexer=s,k.inlineLexer=s.output,k.parse=k,"undefined"!=typeof module&&"object"==typeof exports?module.exports=k:"function"==typeof define&&define.amd?define(function(){return k}):e.marked=k}(this||("undefined"!=typeof window?window:global));
// -------------------- markdownCss样式 --------------------
markcss='.markdown_views{font-family:-apple-system,SF UI Text,Arial,PingFang SC,Hiragino Sans GB,Microsoft YaHei,WenQuanYi Micro Hei,sans-serif,SimHei,SimSun}.markdown_views P{font-size:16px;color:#4f4f4f;font-weight:400;line-height:26px;margin:0 0 16px;text-align:justify}.markdown_views strong{font-weight:700}.markdown_views i,address,cite,dfn,em,var{font-style:italic}.markdown_views *{box-sizing:border-box}.markdown_views h1,.markdown_views h2,.markdown_views h3,.markdown_views h4,.markdown_views h5,.markdown_views h6{color:#4f4f4f;margin:8px 0 16px;font-weight:700}.markdown_views ol,.markdown_views ul{margin:0 0 24px;padding:0}.markdown_views ul ol{margin:0 0 24px 32px}.markdown_views ul li{list-style-type:disc;margin:8px 0 0 32px}.markdown_views ol li{list-style-type:decimal;margin-left:40px;margin-top:8px}.markdown_views img{margin:24px 0;max-width:100%}.markdown_views h1{font-size:28px;line-height:36px}.markdown_views h2{font-size:24px;line-height:32px}.markdown_views h3{font-size:22px;line-height:30px}.markdown_views h4{font-size:20px;line-height:28px}.markdown_views h5{font-size:18px;line-height:26px}.markdown_views h6{font-size:16px;line-height:24px}.markdown_views h1 code{font-size:28px}.markdown_views h2 code{font-size:24px}.markdown_views h3 code{font-size:22px}.markdown_views h4 code{font-size:20px}.markdown_views h5 code{font-size:18px}.markdown_views h6 code{font-size:16px}.markdown_views blockquote{display:block;padding:16px;margin:0 0 24px;border-left:8px solid #DDDFE4;background:#EEF0F4;overflow:auto;overflow-scrolling:touch;word-wrap:normal;word-break:normal}.markdown_views blockquote ol,.markdown_views blockquote ul{margin-bottom:0;padding:0;font-size:14px;line-height:22px}.markdown_views blockquote ol li,.markdown_views blockquote ul li{margin-bottom:0}.markdown_views blockquote p{font-size:14px;line-height:22px;color:#999;font-weight:400;margin-bottom:0}.markdown_views hr{margin:24px 0;border:none;border-bottom:solid #ddd 1px}.markdown_views table tr{border:0;border-top:1px solid #DDD;background-color:#fff}.markdown_views table{border-collapse:collapse;display:table;width:100%;text-align:center;margin-bottom:24px}.markdown_views tbody{border:0}.markdown_views table tr:nth-child(2n){background-color:#F7F7F7}.markdown_views table tr td,.markdown_views table tr th{font-size:14px;color:#4f4f4f;line-height:22px;border:1px solid #DDD;padding:8px;text-align:left;word-wrap:break-word;word-break:normal;vertical-align:middle}.markdown_views table tr td code,.markdown_views table tr th code{white-space:normal;word-break:break-all}.markdown_views table tr th{font-weight:700;background-color:#eff3f5}.markdown_views dl{margin:24px}.markdown_views dl dt{margin:8px;font-weight:700}.markdown_views dl dt dd{margin:8px}.markdown_views abbr[data-original-title],.markdown_views abbr[title]{cursor:help;border-bottom:1px dotted #999}.markdown_views .initialism{font-size:90%;text-transform:uppercase}.markdown_views pre{margin-bottom:24px}.hljs{display:block;padding:8px}.hljs-comment,.hljs-comment *,.hljs-javadoc,.hljs-template_comment{color:#800}.clojure .hljs-built_in,.hljs-keyword,.hljs-list .hljs-title,.hljs-request,.hljs-status,.hljs-tag .hljs-title,.hljs-winutils,.http .hljs-title,.method,.nginx .hljs-title,.setting .hljs-value,.tex .hljs-command{color:#008}.hljs-envvar{color:#660}.hljs-attr_selector,.hljs-cdata,.hljs-date,.hljs-filter .hljs-argument,.hljs-regexp{color:#080}.clojure .hljs-attribute,.css .hljs-function,.css .hljs-value .hljs-number,.hljs-decorator,.hljs-hexcolor,.hljs-literal,.hljs-number,.hljs-pi,.hljs-prompt,.hljs-shebang,.hljs-sub .hljs-identifier,.hljs-symbol,.hljs-tag,.hljs-tag .hljs-keyword,.ini .hljs-title{color:#066}.clojure .hljs-title,.haskell .hljs-type,.hljs-built_in,.hljs-class .hljs-id,.hljs-class .hljs-title,.hljs-doctype,.hljs-javadoctag,.hljs-params,.hljs-phpdoc,.hljs-tag .hljs-attribute,.hljs-typename,.hljs-variable,.hljs-yardoctag,.setting{color:#4f4f4f}.css .hljs-tag,.hljs-pseudo,.hljs-rules .hljs-property{color:#000}.css .hljs-class,.css .hljs-id{color:#9b703f}.hljs-value .hljs-important{color:#f70;font-weight:700}.hljs-rules .hljs-keyword{color:#c5af75}.apache .hljs-sqbracket,.hljs-annotation,.nginx .hljs-built_in{color:#9b859d}.tex .hljs-formula{background-color:#eee;font-style:italic}.diff .hljs-header,.hljs-chunk{color:grey;font-weight:700}.diff .hljs-change{background-color:#bccff9}.hljs-addition{background-color:#baeeba}.hljs-deletion{background-color:#ffc8bd}.hljs-comment .hljs-yardoctag{font-weight:700}.apache .hljs-cbracket,.apache .hljs-tag,.asciidoc .hljs-header,.bash .hljs-variable,.coffeescript .hljs-attribute,.django .hljs-variable,.erlang_repl .hljs-function_or_atom,.haml .hljs-symbol,.hljs-addition,.hljs-aggregate,.hljs-constant,.hljs-flow,.hljs-parent,.hljs-pragma,.hljs-preprocessor,.hljs-preprocessor *,.hljs-rules .hljs-value,.hljs-rules .hljs-value .hljs-number,.hljs-stream,.hljs-string,.hljs-tag .hljs-value,.hljs-template_tag,.hljs-title,.markdown .hljs-header,.ruby .hljs-symbol,.ruby .hljs-symbol .hljs-string,.smalltalk .hljs-class,.tex .hljs-command,.tex .hljs-special{color:#090}.clojure .hljs-built_in,.hljs,.hljs-subst,.hljs-tag .hljs-title,.lisp .hljs-title,.nginx .hljs-title{color:#4f4f4f}.apache .hljs-cbracket,.apache .hljs-tag,.asciidoc .hljs-header,.bash .hljs-variable,.coffeescript .hljs-attribute,.django .hljs-variable,.erlang_repl .hljs-function_or_atom,.haml .hljs-symbol,.hljs-addition,.hljs-aggregate,.hljs-constant,.hljs-flow,.hljs-parent,.hljs-pragma,.hljs-preprocessor,.hljs-rules .hljs-value,.hljs-rules .hljs-value .hljs-number,.hljs-stream,.hljs-string,.hljs-tag .hljs-value,.hljs-template_tag,.hljs-title,.markdown .hljs-header,.ruby .hljs-symbol,.ruby .hljs-symbol .hljs-string,.smalltalk .hljs-class,.tex .hljs-command,.tex .hljs-special{color:#090}.markdown_views code,.markdown_views kbd,.markdown_views pre,.markdown_views samp{font-family:Consolas,Inconsolata,Courier,monospace;font-size:14px;line-height:22px;color:#000}.markdown_views code{color:#c7254e;background-color:#f9f2f4;border-radius:2px;padding:4px 2px 0}.markdown_views a{color:#4EA1DB;text-decoration:none}.markdown_views a:focus,.markdown_views a:hover{color:#ca0c16}.markdown_views a:visited{color:#6795B5}.markdown_views .footnote{vertical-align:top;position:relative;top:-4px;font-size:12px}.markdown_views .footnotes ol li{font-size:14px;line-height:22px;margin:0 0 8px 24px}.markdown_views .flow-chart,.markdown_views .sequence-diagram{text-align:center;margin-bottom:24px;font-size:14px!important}.markdown_views .flow-chart [fill="#000"],.markdown_views .flow-chart [fill="#000000"],.markdown_views .flow-chart [fill=black],.markdown_views .sequence-diagram [fill="#000"],.markdown_views .sequence-diagram [fill="#000000"],.markdown_views .sequence-diagram [fill=black]{fill:#4f4f4f}.markdown_views .flow-chart [stroke="#000000"],.markdown_views .sequence-diagram [stroke="#000000"]{stroke:#4f4f4f}.markdown_views .MathJax_SVG_Display{text-align:center;margin:24px 0;font-size:18px;font-weight:400;color:#4f4f4f;position:relative;text-indent:0;max-width:none;max-height:none;min-width:0;min-height:0;width:100%}.markdown_views .toc{font-size:16px;line-height:24px;margin:0 0 24px;padding:0}.markdown_views .toc ul{margin:0 0 8px;padding:0}.markdown_views .toc ul li{list-style-type:none;margin:8px 0 0 24px}.markdown_views pre code{display:block;font-size:14px;line-height:22px;overflow-x:auto;padding:0;color:#000;white-space:pre;word-wrap:normal;background-color:#f6f8fa;border-radius:4px}.markdown_views .prettyprint,.markdown_views pre.prettyprint{margin:0 0 24px;padding:8px 16px 4px 56px;background-color:#f6f8fa;border:none}.prettyprint{position:relative;overflow-y:hidden;overflow-x:auto}.markdown_views .prettyprint .pre-numbering{position:absolute;width:48px;background-color:#eef0f4;top:0;left:0;margin:0;padding:8px 0;list-style:none;text-align:right}.markdown_views .pre-numbering li{padding:0 8px;list-style:none;margin:0}.markdown_views dl dd{margin:0 0 8px 40px}.markdown_views kbd{padding:2px 8px;border:1px solid rgba(63,63,63,.25);box-shadow:0 1px 0 rgba(63,63,63,.25);background-color:#fff;color:#333;border-radius:4px;display:inline-block;margin:0 2px;white-space:nowrap}'
markcss2='#Toc2{/*禁止被选择*/-webkit-touch-callout: none; /* iOS Safari */;-webkit-user-select: none; /* Chrome/Safari/Opera */;-khtml-user-select: none; /* Konqueror */;-moz-user-select: none; /* Firefox */;-ms-user-select: none; /* Internet Explorer/Edge */;user-select: none; /* Non-prefixed version, currently;not supported by any browser */;}#toc ul, #toc li{padding:0;margin:0;list-style:none;margin-left:8}a{text-decoration:none}'
// tocs=document.body.firstChild.textContent.split("\n")

// -------------------- 定义变量 --------------------
var markcss;var markcss2;var content;var a;var i;

// -------------------- 脚本开始 --------------------
// 判断打开的文件是否本地markdown
if (document.body.firstChild.nodeName == 'PRE'){
    // 添加CSS样式
    document.head.innerHTML=document.head.innerHTML+'<style type="text/css">'+markcss+'</style>'+'<style type="text/css">'+markcss2+'</style>';
    // 若窗口大小改变则自动更改显示
    document.body.setAttribute("onresize",'document.getElementById("container").style.height=window.innerHeight-20;document.getElementById("container").style.width=window.innerWidth-20;document.getElementById("content").style.width=window.innerWidth-232');

// -------------------- 初始化body --------------------
    // 或者使用frameset(document.body.parentElement.innerHTML能修改整个HTML)
    document.body.innerHTML='<iframe name="MarkdownIframe" id="MarkdownView" src="SUMMARY.md" style="display:none"></iframe>\
    <div id="container" style="border:1px solid #E0E0E0;height:'+(window.innerHeight-20).toString()+'px;width:'+(window.innerWidth-20).toString()+'px;">\
    <div id="toc" style="display:block;border-right:1px solid #E0E0E0;float:left;width:200px;height:100%;overflow-x:auto;overflow-y:auto;white-space:nowrap;">Loading...</div>\
    <div id="Toc3" style="display:none;border-right:1px solid #E0E0E0;float:left;width:200px;height:100%;overflow-x:auto;overflow-y:auto;white-space:nowrap;">Loading...</div>\
    <div id="content" class="markdown_views" style="float:left;overflow-y:auto;height:100%;width:'+(window.innerWidth-232).toString()+'px;padding-left:10px;">'+marked(document.body.firstChild.textContent)+'</div>\
    <div id="Toc2" style="position:absolute;left:190;top:3px;px;width:40px;height:20px;border-radius:0 0 40px 40px;background:#E0E0E0;text-align:center;color:#FFF">TOC</div>\
    </div>'

// -------------------- Toc2鼠标点击事件 --------------------
    // 循环切换书籍目录和文章目录的显示
    document.getElementById("Toc2").setAttribute("onclick",'if( document.getElementById("toc").style.display=="block"){document.getElementById("Toc3").style.display="block";document.getElementById("toc").style.display="none"}else{document.getElementById("Toc3").style.display="none";document.getElementById("toc").style.display="block"}');

// -------------------- markdown视图内所有h标签转为目录 --------------------
    a = document.getElementById("content").querySelectorAll("h1,h2,h3,h4,h5,h6")
    txt=""
    for(i=0,len=a.length;i<len;i++){
        nunu="&#8195;&#8195;".repeat(Number(a[i].tagName.slice(-1)) - 1);
        a[i].id=a[i].textContent;
        txt=txt+"<a href='#"+a[i].textContent +"'>"+nunu+a[i].textContent+"</a><br>";}
    document.querySelector("#Toc3").innerHTML=txt

// --------------------等待ifarm(MarkdownView)加载完成之后的事件--------------------
    document.getElementById("MarkdownView").onload=function(){

    // -------------------- 定义变量 --------------------
        var MarkdownView;var a;var i;var len;var txt;var nunu;

        if(document.getElementById("toc").innerText=="Loading..."){
            document.getElementById("toc").innerHTML=marked(parent.document.getElementById("MarkdownView").contentDocument.body.firstChild.textContent);
            // 删除SUMMARY的标题
            document.getElementById("toc").removeChild(document.getElementById('summary'));
        // -------------------- 设置所有SUMMARY目录超链接用iframe方式打开 --------------------
            // 此设置首先需要页面内有iframe标签,且标签具有name属性
            a=document.getElementById("toc").querySelectorAll('a');
            for (i in a){a[i].target="MarkdownIframe"};
        }
        else{
            // 获取iframe的内容
            MarkdownView=parent.document.getElementById("MarkdownView").contentDocument.body.firstChild.textContent;
            // 显示iframe的内容
            document.querySelector('.markdown_views').innerHTML=marked(MarkdownView)
        }

    // -------------------- markdown视图内的a标签链接打开方式转为新窗口打开 --------------------
        a = document.querySelectorAll(".markdown_views a");
        for (i=0, len=a.length; i<len; i++) {a[i].target = "_blank"};

    // -------------------- 释放变量 --------------------
        delete MarkdownView;delete a;delete nunu;delete txt;delete i;delete len;
    };
}

// -------------------- 释放变量 --------------------
delete markcss;delete markcss2;delete content;delete a;delete i;

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

466162659 发表于 2018-8-3 18:54
你好歹解释下,具体效果...........这代码有点不敢接
 楼主| 763221847 发表于 2018-8-3 19:03
466162659 发表于 2018-8-3 18:54
你好歹解释下,具体效果...........这代码有点不敢接


要嘛解释呢.
脚本放好再把markdown往浏览器拖就O几把K了.....
xyy808 发表于 2018-8-3 19:58
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-30 05:53

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表