根据文章中H标签自动生成文章目录

2013/10/11 2543点热度 0人点赞 0条评论

以前看到csdn上的目录结构就想把它移植到博客里,今天抽了个空从csdn上拔下了代码。

js代码,复制放入到single.php页面中

<script type="text/javascript">// < ![CDATA[
jQuery(document).ready(function(){
               buildCTable();
});
function buildCTable() {
    var hs = jQuery(".entry-content").find("h1,h2,h3,h4,h5,h6");
    if (hs.length < 2) return;
    var s = "";
    s += '<div style="clear:both"></div>';
    s += '<div class="roundDiv" >';
    s += '<p style="text-align:right;margin:0;"><span style="float:left;color:#F00">目录<a href="#" title="系统根据文章中H1到H6标签自动生成文章目录">(?)</a></span><a href="#" onclick="javascript:return openct(this);" title="展开">[+]</a></p>';
    s += '<ol style="display:none;margin-left:14px;padding-left:14px;line-height:160%;">';
    var old_h = 0, ol_cnt = 0;
    for (var i = 0; i < hs.length; i++) {
        var h = parseInt(hs[i].tagName.substr(1), 10);
        if (!old_h) old_h = h;
        if (h > old_h) {
            s += "<ol>";
            ol_cnt++;
        } else if (h < old_h && ol_cnt > 0) {
            s += "</ol>";
            ol_cnt--;
        }
        if (h == 1) {
            while (ol_cnt > 0) {
                s += "</ol>";
                ol_cnt--;
            }
        }
        old_h = h;
        var tit = hs.eq(i).text().replace(/^[\d.、\s]+/g, "");
        tit = tit.replace(/[^a-zA-Z0-9_\-\s\u4e00-\u9fa5]+/g, "");
        if (tit.length < 100) {
	    //将每一个h标签拼接到s上,生成目录
            s += '<li><a href="#t' + i + '">' + tit + "</a></li>";
	    //给文章中的h标签加上id
            hs.eq(i).html('<a name="t' + i + '"></a>' + hs.eq(i).html());
        }
    }
    while (ol_cnt > 0) {
        s += "</ol>";
        ol_cnt--;
    }
    s += "</ol></div>";
    s += '<div style="clear:both"></div>';
    jQuery(s).insertBefore(jQuery(".entry-content"));
}

function openct(e) {
    if (e.innerHTML == "[+]") {
        jQuery(e).attr("title", "收起").html("[-]").parent().next().show();
    } else {
        jQuery(e).attr("title", "展开").html("[+]").parent().next().hide();
    }
    e.blur();
    return false;
}
// ]]></script>

带圆角的div框

.roundDiv{
   float:left; 
   min-width:200px;
   margin: 4px  10px;
   position: relative!important;
   overflow: auto!important;
   background-color: #eee!important;
   border: 1px solid #ccc!important;
   border-radius: 4px!important;
   border-collapse: separate!important;
}

yxkong

这个人很懒,什么都没留下

文章评论