怎么让博客园文章支持生成目录索引
来源:互联网 发布:淘宝超级运动会内容 编辑:程序博客网 时间:2024/05/22 12:47
用过markdown的同学都知道,生成目录索引的标签是
[TOC]
,但是博客园markdown编辑器不支持[TOC]
标签,于是决定自己实现目录索引功能。
[TOC]
1. 实现思路
博客园会把
[TOC]
标签原样显示出来<p>[TOC]</p>
,所以我们可以遍历文章的所有h1、h2、h3标签依次组合成目录列表,然后替换掉<p>[TOC]</p>
。
2. JS代码
我这里把生成目录功能写成一个jquery插件Catalog,使用的时候直接
$( "#cnblogs_post_body" ).catalog()
,CSS样式这里就不贴了,大家可以根据自己喜好编写CSS样式。
( function( $ ) { function Catalog( element, options ) { this.$parentEle = $( element ); this.$catalog_container = $( "<div>" ); this.$catalog_title = $( "<h1>" ); this.$ul_container = $( "<ul>" ); this.$control_a = $( "<button>" ); this.titleReg = /^h[1-3]$/; this.static = true; this.init( this ); } Catalog.prototype = { init: function( self ) { // 组合目录容器和标题等 self.$catalog_title.text( '目录' ); self.$catalog_container.attr( "id", "catalog" ) .append( self.$catalog_title ) .append( self.$control_a.attr( "class", "control_btn").text( "-" ) ); // 查找文章中所有的h1、h2、h3标签 // 生成目录列表插入目录容器中 self.$parentEle.children().each( function() { if( self.titleReg.test( this.tagName.toLowerCase() ) ) { $( this ).append( "<a href='#catalog' class='title_back'> #</a>" ); self.$ul_container.append( self.list( this ) ); } } ); // 替换[TOC]为目录 $( "#cnblogs_post_body > p" ).eq(0).replaceWith(self.$catalog_container.append(self.$ul_container)); // 添加目录收缩功能 $( "#catalog > button" ).on( "click", function() { $( "#catalog ul" ).toggle(); $( event.target ).text( self.static ? "+" : "-" ); self.static = !self.static; } ); }, // 生成目录列表函数 list: function( element ) { var aEle = $( "<a></a>" ), hEle = $( "<li></li>" ); aEle.attr( "href", "#" + element.id ).text( element.childNodes[0].nodeValue ); hEle.attr( "class", element.nodeName.toLowerCase() + "_list" ).append( aEle ); return hEle; }, }; $.fn.catalog = function( options ) { return this.each( function() { if( !$.data( this, 'catalog' ) ) { $.data( this, 'catalog', new Catalog( this, options ) ); } } ); } // 使用插件 $( "#cnblogs_post_body" ).catalog();} )( window.jQuery );
基本功能完成了,虽然简单但是能凑合着用。
3. 使用
- 申请开通JS接口
- “管理” -> “设置” -> “页脚HTML”,直接把代码拷贝进去。(注意:代码头尾需要加
<script></script>
标签)
1 0
- 怎么让博客园文章支持生成目录索引
- TeacherWhat博客文章目录索引
- 博客目录索引
- 数字图像处理 博客目录索引
- 本博客全文目录索引
- MarkDown生成目录索引
- 怎么让系统支持S1
- 怎么让网站站内文章秒收录
- 怎么让tomcat支持中文文件名???
- 怎么让blackberry的模拟器支持中文?
- 怎么让Nginx/apache支持shtml格式
- 【转】怎么让VI支持中文显示
- 怎么才能让博客访问流量大
- 目录索引
- 让Octopress为文章自动生成目录
- 转载:博客园文章
- 博客园+CSDN文章
- 朋友博客园文章
- 银行家算法。多类型资源死锁检测模…
- 海量数据处理:十道面试题与十个海…
- QString和QDateTime之间的相…
- 多线程:线程间协作
- QT SQL数据库操作流程
- 怎么让博客园文章支持生成目录索引
- Linux下安装Redis
- 程序重新打开的时候无法加载出新加…
- springMVC接收多个对象
- BZOJ4399: 魔法少女LJJ treap
- 创建和打开文件,输出和写入
- springMVC执行流程详解
- Linux系统inode全知道
- Python中的几个高级数据结构