联系官方销售客服
1835022288
028-61286886
获取文章所有的h标签,生成目录,增加跳转js
点击 当前页内跳转
自动识别当前位置 进行赋值active
个人比较菜,扣了半天才搞出来,拿去参考,有不足之处大家帮忙指正
右侧目录代码 主要是id
<div class="col-lg-3 col-md-12 col-12"> <div class="header"> <h6 class="title title-1">目录</h6> </div> <div id="groupfile"> </div> </div>
左侧文章代码
<div class="entry-wrapper"> <div class="entry-content u-text-format u-clearfix" id="content"> {$content} </div> </div>
js代码
// 首先根据id获取id下所有H标签 var content=document.getElementById("content"); var headList = [...content.querySelectorAll('h1,h2,h3,h4,h5,h6')]; // 将获取的H标签构造成树 var root = { children: [] }; var h = { node: headList[0], children: [], parent: root }; root.children.push(h); headList.reduce(function (pre, cur) { var n = { node: cur, children: [] } while (h.node.localName[1] - n.node.localName[1] !== -1) { h = h.parent; if (h === root) { break; } } n.parent = h; h.children.push(n); h = n; return h; }); // 给H标签加id var index = 0; function createList(list) { var text = list.reduce(function (pre, cur) { cur.node.id = 'header' + index++; var childText // 判断该H标签有没有子层H标签 if (cur.children.length) { childText = createList(cur.children) } else { childText = '' } pre += ` <li class="groupfile-list"> <a class="catalog-tag" href="#${cur.node.id}"> ${cur.node[xss_clean]} </a> ${childText} </li> ` //目录的列表 return pre; }, ''); var text = ` <ul class=""> ${text} </ul>` return text; } //循环出目录 var content = createList(root.children); document.getElementById('groupfile')[xss_clean] = content; var left_div_top = 100; //左侧边栏距离顶部高度 var right_nav_top = 150; //右侧标题距离浏览器窗口顶部距离(距离顶部多少就切换左侧标题高亮) var groupfile_list = $("#groupfile .groupfile-list>a"); // 获取左侧标题列表dome var groupfile_list1 = $("#groupfile .groupfile-list"); // 获取左侧标题列表dome,用来给li加active //滚动条事件 $(window).scroll(function () { var windouWidth = $(this).width();//获取浏览器自身宽度 var windouHeight = $(this).height();//获取浏览器自身高度 //获取滚动条的滑动距离 var scroH = $(this).scrollTop(); // 滚动js if ($(".main").offset()) { // js判断标题高亮 $(headList).each(function (index, element) { if ($("#header" + (index)).offset().top + windouHeight - right_nav_top < scroH + windouHeight) { $(groupfile_list1[index-1]).removeClass("active"), $(groupfile_list1[index]).addClass("active") } else { $(groupfile_list1[index]).removeClass("active") } }); } }); // 目录跳转js groupfile_list.click(function (e) { e.preventDefault(); var annname = $(this).attr("href"); $('html, body').animate({ scrollTop: $(annname).offset().top - left_div_top }, 100) });
用你的例子出来这个