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

使用jQuery slideToggle切换内容时,如何关闭已打开的div?

解决点击新按钮时自动关闭已打开内容的问题

嘿,你的需求我get到了——每次点击新的「view prices」按钮时,得先把之前展开的内容收起来,再展开新的内容对吧?咱们来优化下代码,轻松实现这个效果。

优化思路

  1. 给所有内容div加个通用类(比如service-content),这样能一次性选中所有需要控制的内容框,不用重复写一堆选择器;
  2. 给每个按钮加个data-target属性,直接关联对应的内容框类名,以后加新按钮不用改JS,扩展性拉满;
  3. 点击按钮时先判断当前内容是否已经展开:
    • 如果已经展开,直接收起它;
    • 如果没展开,先把所有内容框都收起,再展开当前目标内容。

修改后的完整代码

第一步:更新HTML(添加通用类和关联属性)

<div class="heroIcons">
  <div class="button" data-target="waxing">
    <p>view prices</p>
  </div>
  <div class="button" data-target="facials">
    <p>view prices</p>
  </div>
  <div class="button" data-target="bodywraps">
    <p>view prices</p>
  </div>
</div>
<div class="section services">
  <div class="wrapper">
    <div class="service-content waxing">
      <p>Waxing content that I want to slidetoggle</p>
    </div>
  </div>
</div>
<div class="section services">
  <div class="wrapper">
    <div class="service-content facials">
      <p>Facials content that I want to slidetoggle</p>
    </div>
  </div>
</div>
<div class="section services">
  <div class="wrapper">
    <div class="service-content bodywraps">
      <p>Body wraps content that I want to slidetoggle</p>
    </div>
  </div>
</div>

第二步:简化CSS(用通用类统一控制隐藏)

.service-content { display: none; }

第三步:优化后的jQuery代码

$(".heroIcons .button").click(function(){
  // 获取当前按钮对应的目标内容框选择器
  var targetSelector = "." + $(this).data("target");
  var targetContent = $(targetSelector);
  
  // 判断目标内容是否处于显示状态
  if(targetContent.is(":visible")){
    // 已显示,直接收起
    targetContent.slideUp(1500);
  } else {
    // 未显示,先收起所有内容,再展开当前目标(用回调保证动画流畅)
    $(".service-content").slideUp(1500, function(){
      targetContent.slideDown(1500);
    });
  }
});

代码小说明

  • data-target属性:让按钮和内容框直接绑定,不用给每个按钮写单独的点击事件,后续加新服务只要复制按钮和内容框,改个类名就行;
  • 回调函数:确保所有内容框完全收起后再展开新内容,动画不会显得乱糟糟;
  • 通用类:把重复的CSS规则合并,代码更清爽。

这样改完,就能完美实现你要的效果啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:31:22