1 回答
TA贡献1812条经验 获得超5个赞
为文档动态创建链接内容列表的一种方法是首先制作标题的映射,使用:
const allHeadings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
然后您可以遍历地图以构建内容列表:
工作示例:
// GRAB ALL HEADINGS
const allHeadings = document.querySelectorAll('h1, h2, h3, h4, h5, h6');
// CREATE MAP OF HEADINGS
let headingsMap = []
allHeadings.forEach((heading) => {
headingLevel = heading.nodeName.replace('H', '');
headingsMap.push(headingLevel);
});
// BUILD CONTENTS LIST
let contentsList = '';
contentsList += '<div class="contents-list">';
contentsList += '<ul>';
for (let i = 0; i < headingsMap.length; i++) {
allHeadings[i].id = '10' + i;
contentsList += '<li>';
contentsList += '<a href="#10' + i;
contentsList += '">' + allHeadings[i].textContent + '</a>';
switch (true) {
case (i === (headingsMap.length - 1)) :
for (j = 0; j < headingsMap[i]; j++) {
contentsList += '</li></ul>';
}
break;
case (headingsMap[(i + 1)] > headingsMap[i]) :
contentsList += '<ul>';
break;
case (headingsMap[(i + 1)] < headingsMap[i]) :
let difference = (headingsMap[i] - headingsMap[(i + 1)]);
for (j = 0; j < difference; j++) {
contentsList += '</li></ul>';
}
break;
}
}
contentsList += '</div>';
// ADD CONTENTS LIST TO PAGE
let contentsListTemplate = document.createElement('template');
contentsListTemplate.innerHTML = contentsList;
document.body.insertBefore(contentsListTemplate.content, document.body.querySelector('*'));
.contents-list {
color: rgb(127, 0, 0);
font-size: 14px;
line-height: 28px;
text-transform: uppercase;
background-color: rgb(255, 255, 191);
border: 1px solid rgb(127, 0, 0);
}
.contents-list a {
text-decoration: none;
}
.contents-list a:hover {
text-decoration: underline;
}
<h1> This is 1st main Heading1 </h1>
<h2> This is h2 under h1 </h2>
<h3> This is h3 under h1 and h2 </h3>
<h2> This is h2 </h2>
<h3> This is h3</h3>
<h1> This is 2nd main Heading1 </h1>
<h2> This is h2 under h1 </h2>
<h2> This is another h2 under h1 </h2>
<h3> This is h3 </h3>
<h4> This is h4 </h4>
<h2> This is h2 </h2>
添加回答
举报