给WordPress网站文章添加目录、多级标题标记、标题锚点
2022-07-29 10:13:20
119
{{single.collect_count}}

笔者希望给WordPress文章添加目录多级标题标记标题锚点,以便于长文阅读

  • 目录指的是将文章所有标题根据层次关系列入目录内
  • 多级标题标记指的是可以根据图标判断当前是几级标题
  • 标题锚点指的是点击图标页面中心即可跳转到该标题

目录

首先对于目录,这就比较简单了,直接下载WordPress插件“简单的目录”(也就是easy table of contents

image-20220226143001060

随后在设置中进行相应设置即可

image-20220226143045232

该插件会自动将文章中的标题列入目录中,效果如下

image-20220226142340099

多级标题标记和标题锚点

我们经常会在一些笔记网站看到多级标题标记标题锚点功能,如

image-20220226143224939

要想美观地添加多级标题标记,首先先自己准备1级至6级标题的图标,下述代码中的titleAnchorImgDirUrl表示其路径

image-20220226142517837

随后在服务器上找到WordPress站点目录,如笔者的是/www/wwwroot/[站点文件名]

在目录底下找到 wp-content/themes/[WordPress使用的主题名称]/footer.php

</body>之前添加以下代码(需要在已经添加了上述目录插件的基础上才能有效)

<script type="text/javascript">//多级标题图标的路径let titleAnchorImgDirUrl=img/';var blogContentBox=document.getElementsByClassName("single-entry-summary")[0];var titleAnchor=document.createElement("a");var titleAnchorImg=document.createElement("img");//给多级标题图标设置"blog-title-anchor"便于后续CSS调整样式titleAnchorImg.setAttribute("class","blog-title-anchor");titleAnchor.appendChild(titleAnchorImg);for(i=0;i<blogContentBox.childNodes.length;i++){makeAnchor(blogContentBox.childNodes[i]);}function makeAnchor(blogChildNode){switch(blogChildNode.tagName){case "H1":case "H2":case "H3":case "H4":case "H5":case "H6": let newTitleAnchor=titleAnchor.cloneNode(true);newTitleAnchor.firstChild.setAttribute("src",titleAnchorImgDirUrl+blogChildNode.tagName+".png");//根据标题级别选择相应图标newTitleAnchor.setAttribute("href","#"+blogChildNode.firstChild.getAttribute("id"));//设置跳转功能blogChildNode.insertBefore(newTitleAnchor,blogChildNode.firstChild); break;default:break;}}</script>

再简单添加一点CSS样式

/*博客n级标题锚点*/.blog-title-anchor{width: 0.9em;height: 0.9em;margin-right:0.5em;margin-bottom:0.2em; cursor: pointer;}/*博客n级标题悬浮*/.single-content h2:hover,.single-content h3:hover,.single-content h4:hover,.single-content h5:hover,.single-content h6:hover{color:#686868DD;transition: all 0.3s ease;}

即可大功告成

image-20220226142401168

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}