Generate markdown files' table of contents or anchor links menu automatically

Generate markdown files' table of contents or anchor links menu automatically, make markdown files easy to read

当前为 2020-01-14 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Generate markdown files' table of contents or anchor links menu automatically
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.3
  5. // @description Generate markdown files' table of contents or anchor links menu automatically, make markdown files easy to read
  6. // @author FWX
  7. // @include https://github.com/*
  8. // @include https://*.muc*.cn/*
  9. // @grant none
  10. // @require https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js
  11. // ==/UserScript==
  12.  
  13. (function () {
  14. 'use strict';
  15.  
  16. var detect = function (){
  17. var links = $('a.anchor');
  18. var html = '';
  19. var $wrap = '';
  20. var winH = window.screen.availHeight || window.screen.height;
  21. if (!links || !links.length) {
  22. return false;
  23. }
  24. html = '<div id="wx-mkd-toc" style="z-index: 9999; position: fixed; bottom: 50px; right: 20px; background: #f2f2f2; padding: 10px; border: 1px solid #f2f2f2;"><h1 style="margin: 0; font-size: 16px;"><a href="javascript:;"><span>+</span>目录预览</a></h1><div class="wx-mkd-con" style="display: none; overflow: hidden; overflow-y: scroll; padding: 20px; max-height: '+ (winH*.5)+'px;"><ul style="margin: 0; padding: 0;">';
  25. $wrap = $('body');
  26. $.each(links, function (idx, item) {
  27. var $this = $(item);
  28. var $p = $this.parent();
  29. var tag = (($p[0] && $p[0].tagName) || '').toLowerCase();
  30. var tagNum = (tag || '').replace(/h/gi, '');
  31. var mLeft = tagNum * 10;
  32. html += '<li style="margin-left: ' + mLeft + 'px;" class="c_toc_' + tag + '"><a href="' + $this.attr('href') + '">' + $p.text() + '</a></li>'
  33. });
  34. html += '</ul></div></div>';
  35. $wrap.prepend(html);
  36.  
  37. $wrap.on('click', '#wx-mkd-toc h1', function(){
  38. var $this = $(this);
  39. var $thisSpan = $this.find('span');
  40. var thisSpanTxt = $thisSpan.text();
  41. var $thisCon = $this.parent().find('.wx-mkd-con');
  42. if(thisSpanTxt.match(/\+/gi)){
  43. $thisCon.show();
  44. $thisSpan.text('-');
  45. } else {
  46. $thisCon.hide();
  47. $thisSpan.text('+');
  48. }
  49. });
  50. };
  51.  
  52. setTimeout(function(){
  53. detect();
  54. }, 2000);
  55.  
  56. })();