自动创建网页文章目录结构

前言:每当我们发布一篇具有较长内容的文章时,在每一个段落前都会该创建一个小标题以表示这一段落所讲的具体内 容。由于文章内容过长的原因用户可能会耗费一些时间去来回查找段落内容,因此如果为文章中创建一个文章目录结构,用户就可以快速的定位到相应的标题段落, 而不需要来回的滚动查找段落内容。

我想这样做的确可以为文章编排的质量加分,所以借此机会分享一个自动生成的网页文章目录结构的方法,以下这张图清楚的演示了文章目录结构的效果。

网页文章目录结构图示

通常情况下我们在写一篇很长的文章时,都会将内容包裹在一个内容成内容层内,例如

<div class="article">
 
<h3 id="question-one">Title of Question</h3>
<!-- whatever other content, probably some paragraphs and stuff. -->
 
<h3 id="question-two">Another Question</h3>
   <!-- whatever other content, probably some paragraphs and stuff. -->
 
   <!-- etc -->
</div>

在HTML5中我们可以这么写

<article>
 
<h3 id="question-one">Title of Question</h3>
<!-- whatever other content, probably some paragraphs and stuff. -->
 
<h3 id="question-two">Another Question</h3>
   <!-- whatever other content, probably some paragraphs and stuff. -->
 
   <!-- etc -->
</article>

正常情况下如果你想添加一个锚链接快速定位到相应的段落,你可以这么写。

<a href="#question-one">Question One</a>
<a href="#question-two">Question two</a>

还是到此为止吧,以上是手动添加锚链接的方式,下面就介绍一下如何利用jquery来为我们自动创建文章目录结构。

step 1: 首先我们先创建一个HTML变量

var ToC =
  "<nav role='navigation' class='table-of-contents'>" +
    "<h2>On this page:</h2>" +
    "<ul>";

Step 2: 接下来循环遍历段落小标题h3

$("article h3").each(function() {
 
  // loop
 
});

Step 3: 接着获取小标题h3的标题内容和标题ID,也就是写文章的时候创建的标题ID

var el, title, link;
 
$("article h3").each(function() {
 
  el = $(this);
  title = el.text();
  link = "#" + el.attr("id");
 
});

Step 4: 创建一个目录结构然后把创建好的目录结构加到 article 元素里面

var newLine, el, title, link;
 
$("article h3").each(function() {
 
  el = $(this);
  title = el.text();
  link = "#" + el.attr("id");
 
  newLine =
    "<li>" +
      "<a href='" + link + "'>" +
        title +
      "</a>" +
    "</li>";
 
  ToC += newLine;
 
});

Step 5: 闭合标签

ToC +=
   "</ul>" +
  "</nav>";

Step 6: 把创建好的目录结构插入到html页面内,大公告成。

$("article").prepend(ToC);

总结:其实整个过程我们要做的就是利用js把文章中每个小段落的标题以及对应的ID都存储起来,接着将存储的数据利用js动态的创建出目录结构。

demo 演示

demo下载

原文地址:https://www.cnblogs.com/dglives/p/3176438.html