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

无需jQuery:优化JS onclick按钮的显示更多/收起功能

优化「显示更多/收起」功能的原生JS实现

优化思路

  • 用类选择器替代硬编码ID,实现组件复用
  • 通过data-target属性建立按钮与目标内容的关联,摆脱JS中硬编码元素ID的限制
  • 编写通用事件处理函数,所有按钮共用逻辑,新增按钮无需修改JS代码

修改后的代码

HTML结构

<!-- 第一个展开/收起组 -->
<div class="expandable-group">
  <div class="expandable-content" id="more-text">
    <!-- 此处放置需要展开的内容 -->
    示例内容1...(可根据实际长度调整CSS的max-height)
  </div>
  <button class="button slide-down show-more-btn" data-target="#more-text">
    SHOW MORE
    <svg width="13px" height="10px" viewBox="0 2 13 10">
      <path d="M 1 5 L 1 5 L 5 9 L 9 5 L 5 9"></path>
    </svg>
  </button>
</div>

<!-- 第二个展开/收起组(新增时直接复制此结构修改ID即可) -->
<div class="expandable-group">
  <div class="expandable-content" id="more-text2">
    <!-- 此处放置第二个需要展开的内容 -->
    示例内容2...
  </div>
  <button class="button slide-down show-more-btn" data-target="#more-text2">
    SHOW MORE
    <svg width="13px" height="10px" viewBox="0 2 13 10">
      <path d="M 1 5 L 1 5 L 5 9 L 9 5 L 5 9"></path>
    </svg>
  </button>
</div>

CSS样式

.expandable-content {
  max-height: 0px;
  overflow: hidden;
  transition: max-height 0.7s ease;
}
.expandable-content.open {
  transition: max-height 0.7s ease;
}

/* 不同长度内容的高度单独设置 */
#more-text.open {
  max-height: 1600px;
}
#more-text2.open {
  max-height: 600px;
}

原生JS逻辑

// 获取所有「显示更多」按钮
const showMoreButtons = document.querySelectorAll('.show-more-btn');

// 通用点击处理函数
function toggleExpandContent() {
  // 获取当前按钮对应的目标内容元素
  const targetSelector = this.getAttribute('data-target');
  const content = document.querySelector(targetSelector);
  
  // 获取按钮内的SVG和路径元素
  const svg = this.querySelector('svg');
  const path = this.querySelector('path');
  
  // 切换内容的展开状态
  const isExpanded = content.classList.toggle('open');
  
  // 更新按钮文本与SVG状态
  if (isExpanded) {
    this.innerHTML = this.innerHTML.replace('MORE', 'LESS');
    svg.setAttribute('viewBox', '0 -2 13 10');
    path.setAttribute('d', 'M 1 5 L 1 5 L 5 1 L 9 5 L 5 1');
  } else {
    this.innerHTML = this.innerHTML.replace('LESS', 'MORE');
    svg.setAttribute('viewBox', '0 2 13 10');
    path.setAttribute('d', 'M 1 5 L 1 5 L 5 9 L 9 5 L 5 9');
  }
}

// 给每个按钮绑定点击事件
showMoreButtons.forEach(button => {
  button.addEventListener('click', toggleExpandContent);
});

优化亮点

  • 无重复代码:新增按钮时只需复制HTML结构,修改data-target指向对应内容ID即可
  • 纯原生实现:不依赖任何第三方库,性能更优
  • 逻辑解耦:按钮与内容通过data属性关联,避免硬编码ID导致的维护问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:15:40