Shopify集合描述添加Read more/less按钮的Liquid实现方法咨询
Shopify集合描述添加Read more/less折叠按钮实现方案
直接替换你模板中原来的{{ collection.description }}代码即可,可自定义预览文本长度,短描述自动隐藏折叠按钮:
{% assign desc_plain_text = collection.description | strip_html %} {% assign preview_truncate_length = 150 %} {% comment %} 上面的150是预览部分的字符长度,可自行修改为你需要的数值 {% endcomment %} {% if desc_plain_text.size > preview_truncate_length %} {% assign preview_content = collection.description | truncate: preview_truncate_length, '' %} {% assign hidden_content = collection.description | remove_first: preview_content %} <div class="collection-desc-wrapper"> {{ preview_content }} <span id="dots-{{ collection.id }}">...</span> <span id="more-{{ collection.id }}" style="display: none;">{{ hidden_content }}</span> </div> <button id="toggle-btn-{{ collection.id }}" onclick="toggleCollectionDesc({{ collection.id }})">Read more</button> <script> function toggleCollectionDesc(collectionId) { const dots = document.getElementById(`dots-${collectionId}`); const moreText = document.getElementById(`more-${collectionId}`); const btn = document.getElementById(`toggle-btn-${collectionId}`); if (dots.style.display === "none") { dots.style.display = "inline"; btn.innerText = "Read more"; moreText.style.display = "none"; } else { dots.style.display = "none"; btn.innerText = "Read less"; moreText.style.display = "inline"; } } </script> {% else %} {{ collection.description }} {% endif %}
注意事项
- 代码中使用集合ID作为唯一标识绑定DOM元素,同页面多个集合模块不会出现功能冲突
- 如果你的集合描述包含大量HTML标签(图片、列表、多段文本等),为避免标签截断导致排版错乱,可将
preview_content的赋值代码修改为{% assign preview_content = collection.description | strip_html | truncate: preview_truncate_length, '' %},让预览部分输出纯文本即可 - 你可以根据需求自行修改按钮的样式、预览截断长度,以及Read more/Read less的文字内容
内容的提问来源于stack exchange,提问作者Code maniacs
相关产品推荐
相关产品推荐

