博客园根据h1 h2 h3添加目录的js代码

说明

当需要从自己所写的博客中较快地找到需要找的地方,没有目录的时候只能不断滚动鼠标来查找,这样查找看得眼睛真心的累。因此,我就花了点时间写了个自动建立目录的代码。该js代码是依据文章内容中的h1.h2和h3三种元素来制定文章的目录的。该代码可以应用到利用markdown编辑器进行博客书写的情况,对于其他的所见即所得的博客编辑器,可能不太适用

js代码

<script>

$(document).ready(function(){
    $("#cnblogs_post_body").prepend("<div id='cot'><a id='cot_toggle' href='#'>[目录+]</a></div>");
    $("#cot").append("<div id='cot_body'></div>");
    $("#cot_body").css("display","none");

    $("#cnblogs_post_body").children("h1").each(function(h1_index){
        var h1 = $(this);
		var i = h1_index+1;
		$("#cot_body").append(
			'<div class="cot_h1">'
			+ i + ' '
			+ '<a href="#' + h1.attr("id") + '">' 
			+ h1.html() 
			+ '</a></div>');
		
        h1.nextUntil("h1","h2").each(function(h2_index){
            var h2 = $(this);
			var j = h2_index+1;
			$("#cot_body").append(
				'<div class="cot_h2">'
				+ i + '.' + j + ' '
				+ '<a href="#' + h2.attr("id") + '">' 
				+ h2.html() 
				+ '</a></div>');
            h2.nextUntil("h2","h3").each(function(h3_index){
                var h3 = $(this);
				var k = h3_index+1;
				$("#cot_body").append(
					'<div class="cot_h3">'
					+ i + '.' + j + '.' + k + ' '
					+ '<a href="#' + h3.attr("id") + '">' 
					+ h3.html() 
					+ '</a></div>');
            });
        });
    });
	
	$(".cot_h1").css("marginLeft","10px");
	$(".cot_h2").css("marginLeft","38px");
    $(".cot_h3").css("marginLeft","66px");

    var showCot = false;
    $("#cot_toggle").click(function(){
        if(showCot){
             $("#cot_body").css("display","none");
			 $("#cot_toggle").text("[目录+]");
             showCot = false;
        }else{
             $("#cot_body").css("display","block");
			 $("#cot_toggle").text("[目录-]");
             showCot = true;
        }
    });
});

</script>
原文地址:https://www.cnblogs.com/smallpi/p/7368426.html