概要

設定方法

{
"type": "page_anchor",
"name": "t:sections.main-article.blocks.page_anchor.name"
},
"page_anchor": {
"name": "ページ内リンク"
},

{%- when 'content' -%}
<div
class="article-template__content page-width page-width--narrow rte"
itemprop="articleBody"
{{ block.shopify_attributes }}
>
{%- if article.metafields.custom.page_anchor -%}
{% assign article_content_with_page_anchor = article.content %}
{%- for anchor in article.metafields.custom.page_anchor.value -%}
{% assign replace_text = '<span id="anchor-' | append: forloop.index | append: '">' | append: anchor | append: '</span>' %}
{% assign article_content_with_page_anchor = article_content_with_page_anchor | replace: anchor, replace_text %}
{%- endfor -%}
{{ article_content_with_page_anchor }}
{%- else -%}
{{ article.content }}
{%- endif -%}
</div>
{%- when 'page_anchor' -%}
{%- if article.metafields.custom.page_anchor -%}
<div class="article-template__page_anchor page-width page-width--narrow">
<h4>目次</h4>
<ul>
{%- for anchor in article.metafields.custom.page_anchor.value -%}
<li><a href="#anchor-{{ forloop.index }}">{{ anchor }}</a></li>
{%- endfor -%}
</ul>
</div>
<style>
.article-template__page_anchor {
background-color: #EEE;
padding: 2em;
width: 100%;
}
.article-template__page_anchor h4 {
font-weight: bold;
font-size: 1.2em;
margin: 0 0 1em;
}
.article-template__page_anchor ul {
margin: 0;
padding: 0;
}
.article-template__page_anchor ul > li {
position: relative;
padding-left: 1.7em;
list-style-type: none;
line-height: 1.2em;
margin-bottom: 1em;
}
.article-template__page_anchor ul > li:before {
content: '>';
position: absolute;
left: 0;
font-weight: bold;
color: #FFF;
background-color: #000;
border-radius: 50%;
width: 1.2em;
height: 1.2em;
display: flex;
justify-content: center;
align-items: center;
transform: rotate(90deg);
}
.article-template__page_anchor ul > li:last-child {
margin-bottom: 0;
}
.article-template__page_anchor ul > li a {
color: #333;
}
</style>
<script>
const offset = 44; // オフセット値を指定
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const targetElement = document.querySelector(this.getAttribute('href'));
if (targetElement) {
const targetPosition = targetElement.getBoundingClientRect().top + window.pageYOffset - offset;
window.scrollTo({
top: targetPosition,
behavior: 'smooth'
});
}
});
});
});
</script>
{%- endif -%}
運用手順
