根据html中的标题生成目录
warning:
这篇文章距离上次修改已过185天,其中的内容可能已经有所变动。
要根据HTML中的标题生成目录,你可以使用JavaScript来解析页面上的<h1>
, <h2>
, <h3>
, ... 等标题元素,并创建一个目录列表。以下是一个简单的JavaScript函数,它会遍历文档中所有的标题元素,并创建一个无序列表(ul),列表项(li)中包含指向各个标题的超链接。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Generate Table of Contents</title>
<style>
#toc {
position: fixed;
top: 0;
left: 0;
width: 200px;
}
</style>
</head>
<body>
<div id="toc"></div>
<h1 id="title">This is a Heading 1</h1>
<h2 id="subtitle">This is a Heading 2</h2>
<h3 id="section1">This is a Heading 3</h3>
<h4 id="subsection1">This is a Heading 4</h4>
<script>
function generateTOC() {
var toc = document.createElement("ul");
var headings = document.querySelectorAll('h1, h2, h3, h4');
headings.forEach(function(heading, index) {
var id = heading.id || `heading-${index}`;
heading.id = id;
var li = document.createElement("li");
li.innerHTML = `<a href="#${id}">${heading.textContent}</a>`;
toc.appendChild(li);
});
document.getElementById('toc').appendChild(toc);
}
generateTOC();
</script>
</body>
</html>
在这个例子中,我们创建了一个generateTOC
函数,它遍历页面上所有的h1
、h2
、h3
和h4
元素,并为它们生成一个ID(如果它们还没有的话)。然后,它为每个标题创建一个li
元素,在li
元素中,我们创建了一个超链接,这个超链接的href
属性设置为带有生成的ID的#
符号,这样它就可以直接链接到对应的标题元素。最后,我们将这个目录列表添加到页面上ID为toc
的元素中。
评论已关闭