在shopify博客文章内添加目录结构,可以通过自定义修改代码结构
1)修改原代码结构:
1.编辑模板代码,在模板文件夹sections下找到article有关的文件,以下为我的模板举例
2.点击改文件,找到 {{ article.content }}相关部分
<div class="article__content reading-width rte article-content mt-12 mx-auto">
{{ article.content }}
</div>
3.修改代码,将{{ article.content }}这部分内容替换
<div class="article__content reading-width rte article-content mt-12 mx-auto">
{%- assign toc = "" -%}
{%- assign toc_index = 0 -%}
{%- assign h3_count = article.content | scan: '<h3' | size -%}
{%- if h3_count >= 4 -%}
{%- capture new_content %}
{%- assign content_parts = article.content | split: '<h3' -%}
{%- for part in content_parts %}
{%- if forloop.index == 1 %}
{{ part }}
{%- else %}
{%- assign heading_text = part | split: '</h3>' | first | strip_html | strip -%}
{%- assign heading_text = heading_text | replace: 'data-mce-fragment="1"', '' | replace: 'data-mce-fragment="0"', '' | replace: '>', '' -%}
{%- assign toc_index = toc_index | plus: 1 -%}
{%- assign toc_id = "toc-" | append: toc_index -%}
{%- assign toc = toc | append: "<li style='margin-bottom: 10px;'><a href='#" | append: toc_id | append: "' style='text-decoration:none;color:#007bff;'>" | append: heading_text | append: "</a></li>" -%}
<h3 id="{{ toc_id }}" style="margin-top: 40px; font-size: 1.5em; font-weight: bold; padding-top: 150px; margin-top: -150px;">{{ heading_text }}</h3>
{{ part | split: '</h3>' | last }}
{%- assign toc_html = "<div class='article-toc' style='border: 1px solid #ddd; padding: 20px; margin-bottom: 20px; background-color: #f8f9fa;'><h2 style='margin-bottom: 20px;'>CATALOGS</h2><ul style='list-style-type: none; padding-left: 0;'>" | append: toc | append: "</ul></div>" -%}
{%- endif %}
{%- endfor %}
{%- endcapture %}
{{ toc_html | strip_newlines }}
{%- endif -%}
{{ new_content | safe }}
</div>
4.添加样式,在assets文件中找到article相关的样式文件,以下为我的模板举例
5.添加样式代码,具体样式可以根据自己喜好做出调整,最近喜欢蓝色
.article-toc {
margin-bottom: 20px;
padding: 10px;
background-color: #f4f4f4;
border: 1px solid #ddd;
}
.article-toc h2 {
font-size: 18px;
margin-bottom: 10px;
color:rgb(142,179,198) !important;
font-weight:600;
margin-top:0 !important;
}
.article-toc ul {
list-style-type: none;
padding-left: 0;
}
.article-toc ul li {
margin-bottom: 5px;
}
.article-toc ul li::before {
content: "";
display:contents;
}
.article-toc ul li a {
text-decoration: none;
color:rgb(142,179,198) !important;
font-weight:600;
}
.article-toc ul li a:hover {
text-decoration: underline;
}
2)效果展示
3)补充说明
1.专门针对 <h3>
标签进行处理的目录结构,也就是说文章里的标签我使用的都是 <h3>
标签,若使用别的,请相对于做出调整
2.文章中若 <h3>数量小于4默认没有目录结构,大于等于数量4才会显示目录结构
3.建议还是文章比较有“内容”再加,嘤嘤嘤加了目录结构后,被pm说没什么用,隐藏掉了,具体看个人意愿
4.若点目录后页面没有滑动到相对于的位置可以在这里进行调整
<h3 id="{{ toc_id }}" style="margin-top: 40px; font-size: 1.5em; font-weight: bold; padding-top: 150px; margin-top: -150px;">{{ heading_text }}</h3>
5.其实还有其他方法,比如说使用插件什么的,这个看个人,可以研究看看