把js代码放在文章页面里,会在网页加载完毕时,自动生成一个目录。
需要修改lightgallery为自己文章的所在<div>的的id即可。
<!--引用JQuery-->
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js">
</script>
<!--生成文章页目录-->
<script type='text/javascript'>
window.onload = function(){
// 生成目录索引列表
function GenerateContentList() {
var mainContent = $('#lightgallery');
//h2,大标标题内容
var h2_list = $('#lightgallery h2'); //如果你的章节标题不是h2,只需要将这里的h2换掉即可
if (mainContent.length < 1) return;
if (h2_list.length > 0) {
var content = '';
content += '';
content += '
文章目录:
';
content += '
';
//目录遍历
for (var i = 0; i < h2_list.length; i++) {
//回到顶部
var go_to_top = '';
//回到顶部添加
$(h2_list[i]).before(go_to_top);
//h3列表数据
var h3_list = $(h2_list[i]).nextAll("h3");
//console.log("h3l列表数据");
var li3_content = '';
for (var j = 0; j < h3_list.length; j++) {
//h3内容
var tmp = $(h3_list[j]).prevAll('h2').first();
if (!tmp.is(h2_list[i])) break;
var li3_anchor = '';
$(h3_list[j]).before(li3_anchor);
li3_content += '- ' + $(h3_list[j]).text().replace(/:/g, "") + '
';
//查询h4导航内容遍历----2020-06-06\(^o^)/~
var li4_content = ""; //h4遍历的列表数据
var h4_list = $(h3_list[j]).nextAll("h4");
//数据遍历
for (var y = 0; y < h4_list.length; y++) {
//获取第一组h4的值
var tmp4 = $(h4_list[y]).prevAll('h3').first();
//当遍历内容不等于该h3目录下的值时
if (!tmp4.is(h3_list[j])) break;
var li4_anchor = '';
//插入对应的索引
$(h4_list[y]).before(li4_anchor);
li4_content += '- ' + $(h4_list[y]).text() + '
';
}
//console.log("h4遍历结束了");
//h4遍历查询结束
if (li4_content.length > 0) {
li3_content += "";
} else {
li3_content += "";
}
}
var li2_content = '';
if (li3_content.length > 0) li2_content = '- ' + $(h2_list[i]).text().replace(/:/g, "") + '
';
else li2_content = '- ' + $(h2_list[i]).text().replace(/:/g, "") + '
';
content += li2_content;
}
content += '
';
//content += '
';
//content += '文章正文:
';
if ($('#lightgallery').length != 0) {
$($('#lightgallery')[0]).prepend(content);
}
}
}
//执行自动生成目录索引列表
GenerateContentList();
}
</script>
文章评论