很多网站都有根据文章内容,自动提取对应的标题然后组织成文章目录树导航,例如常见的CSDN就实现了目录导航树,如下图
实现思路,遍历详情找出 H1 ~ H6标题标签,然后有序的构造成一棵树并显示到页面中。
JS代码实现:
//构造树 function buildTreeData(tree,node){ if(tree.childrens.length == 0){ tree.childrens.push(node); }else{ var lastNode = tree.childrens[tree.childrens.length - 1]; if(node.tagName > lastNode.tagName ){ buildTreeData(lastNode,node); }else{ tree.childrens.push(node); } } } //初始化生成树 function initTree(note){ var result = $("<li>" + note.text + "</li>"); var size = note.childrens.length; if(size > 0){ var toggle = $("<i title='展开'>[+]</i>"); toggle.on('click', function (e) { // debugger; var children = $(this).next('ul'); if (children.is(":visible")) { children.hide('fast'); $(this).attr('title', '展开').text("[+]"); } else { children.show('fast'); $(this).attr('title', '关闭').text("[-]"); } e.stopPropagation(); }); result.append(toggle); var ul = $("<ul style='display: none;'></ul>"); for(var i=0;i<size;i++){ ul.append(initTree(note.childrens[i])); } result.append(ul); } return result; } //生成目录菜单树 $(function(){ var tree= {tagName:"H0",text:"<span>目录<span>",childrens:[]}; var tags = ['H1','H2', 'H3', 'H4', 'H5', 'H6']; $.each($('#article-content').children(), function(i, val) { if(tags.indexOf(val.tagName) > -1) { var name = "p" + i; $(val).before("<a name='"+name+"'></a>"); var node = { tagName:val.tagName, text:"<a href='#" + name + "'>" + val.textContent + "</a>", childrens:[] }; buildTreeData(tree,node); } }); if(tree.childrens.length > 0){ var menuTres = $("#menu-tree"); menuTres.prepend(initTree(tree)); menuTres.show(); } });
效果展示: