You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify商品描述自动添加Div实现手风琴效果的技术问询

解决方案:用Liquid分割并包裹h2区块

嘿,这个需求很典型——要把每个<h2>开头到下一个<h2>之前的内容,自动包裹成独立的div来做手风琴组件,我们可以用Liquid的字符串处理能力轻松实现,不用写复杂的后端逻辑,具体步骤如下:

1. 替换模板中的描述渲染代码

把你原来的这段代码:

<div class="product-single__description rte"> {{ product.description }} </div>

替换成下面的Liquid代码:

<div class="product-single__description rte">
  {% assign description_blocks = product.description | split: '<h2>' %}
  {% for block in description_blocks offset:1 %}
    <div class="class_{{ forloop.index }} accordion-section">
      <h2>{{ block | split: '</h2>' | first }}</h2>
      <div class="accordion-content">
        {{ block | split: '</h2>' | last }}
      </div>
    </div>
  {% endfor %}
</div>

代码逻辑拆解:

  • 先用split: '<h2>'把整个商品描述按<h2>标签拆分成数组,因为原描述通常以<h2>开头,所以数组第一个元素是空字符串,用offset:1跳过它。
  • 循环处理每个拆分后的区块:
    • 把区块再按</h2>拆分,前半部分是h2的文本内容,我们重新把它放回<h2>标签里。
    • 后半部分就是h2之后到下一个h2之前的所有内容,给它套上accordion-content类方便做折叠控制。
    • 自动给每个外层div生成递增的class(class_1、class_2...),同时加通用类accordion-section方便统一样式。

2. 加手风琴的折叠交互(CSS+JS)

光有结构还不够,要让区块能折叠,得补充一点样式和脚本:

CSS示例(加到主题的CSS文件里):

/* 默认隐藏内容区 */
.accordion-section .accordion-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease-in-out;
  margin-top: 8px;
}
/* 激活状态下展开内容 */
.accordion-section.active .accordion-content {
  max-height: 2000px; /* 设一个足够大的值容纳所有可能的内容 */
}
/* 给标题加点击提示样式 */
.accordion-section h2 {
  cursor: pointer;
  position: relative;
}
.accordion-section h2::after {
  content: '▼';
  position: absolute;
  right: 0;
  transition: transform 0.3s;
}
.accordion-section.active h2::after {
  transform: rotate(180deg);
}

JS示例(加到主题的JS文件或模板底部):

// 给每个h2标题绑定点击事件
document.querySelectorAll('.accordion-section h2').forEach(header => {
  header.addEventListener('click', () => {
    const section = header.closest('.accordion-section');
    section.classList.toggle('active');
  });
});

这样点击每个h2标题,就能切换对应区块的展开/折叠状态了。

注意事项

  • 如果你的商品描述里的h2标签带额外属性(比如class、id),那split: '<h2>'可能会失效,这时候可以先用replace_regex统一处理:
    {% assign cleaned_description = product.description | replace_regex: '<h2[^>]*>', '<h2>' %}
    {% assign description_blocks = cleaned_description | split: '<h2>' %}
    
  • 测试不同商品的描述,确保所有h2区块都被正确包裹,没有遗漏或多余的div。

内容的提问来源于stack exchange,提问作者Davide

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:09:11