根据html中的标题生成目录

要根据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函数,它遍历页面上所有的h1h2h3h4元素,并为它们生成一个ID(如果它们还没有的话)。然后,它为每个标题创建一个li元素,在li元素中,我们创建了一个超链接,这个超链接的href属性设置为带有生成的ID的#符号,这样它就可以直接链接到对应的标题元素。最后,我们将这个目录列表添加到页面上ID为toc的元素中。

none
最后修改于:2024年08月21日 15:46

评论已关闭

推荐阅读

Vue中使用mind-map实现在线思维导图
2024年08月04日
VUE
Web前端最全Vue实现免密登录跳转的方式_vue怎么样不登录返回首页,最强技术实现
2024年08月04日
VUE
vue3 项目搭建教程(基于create-vue,vite,Vite + Vue)
2024年08月04日
VUE
Vue-颜色选择器实现方案——>Vue-Color( 实战*1+ Demo*7)
2024年08月04日
VUE
Vue项目卡顿慢加载?这些优化技巧告诉你!_vue数据多渲染卡顿
2024年08月04日
VUE
vue中的keep-alive详解与应用场景
2024年08月04日
VUE
Vue、React实现excel导出功能(三种实现方式保姆级讲解)
2024年08月04日
vue-office/docx插件实现docx文件预览
2024年08月04日
VUE
java调用js文件的两种方法(支持V8引擎)
2024年08月04日
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2024年08月04日
两周从爬虫小白变大神 _yjs_js_security_passport
2024年08月04日
JS笔记(对象、函数、数组)
2024年08月04日
Markdown.js:强大的纯JavaScript Markdown解析器
2024年08月04日
Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
2024年08月04日
vue 父组件怎么获取子组件里面的data数据
2024年08月04日
VUE
个人开发实现AI套壳网站快速搭建(Vue+elementUI+SpringBoot)
2024年08月04日
el-table 表格封装并改造实现单元格可编辑
2024年08月04日
none
nodejs环境下创建vue项目、SSH密钥登陆!!!
2024年08月04日
vue+quill+element-ui实现视频、图片上传及缩放保姆级教程,轻松使用富文本
2024年08月04日
【three.js】22. Imported Models导入模型
2024年08月04日