首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

打开当前div时关闭其他打开的div (jQuery)

在前端开发中,可以使用jQuery来实现打开当前div时关闭其他打开的div的功能。以下是一个示例代码:

代码语言:txt
复制
<!DOCTYPE html>
<html>
<head>
  <title>打开当前div时关闭其他打开的div</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    .accordion {
      background-color: #f9f9f9;
      color: #444;
      cursor: pointer;
      padding: 18px;
      width: 100%;
      border: none;
      text-align: left;
      outline: none;
      font-size: 15px;
      transition: 0.4s;
    }

    .active, .accordion:hover {
      background-color: #ccc;
    }

    .panel {
      padding: 0 18px;
      display: none;
      background-color: white;
      overflow: hidden;
    }
  </style>
</head>
<body>
  <h2>打开当前div时关闭其他打开的div</h2>

  <button class="accordion">Section 1</button>
  <div class="panel">
    <p>内容1</p>
  </div>

  <button class="accordion">Section 2</button>
  <div class="panel">
    <p>内容2</p>
  </div>

  <button class="accordion">Section 3</button>
  <div class="panel">
    <p>内容3</p>
  </div>

  <script>
    $(document).ready(function() {
      $('.accordion').click(function() {
        $(this).toggleClass('active');
        $(this).next('.panel').slideToggle();

        // 关闭其他打开的div
        $('.accordion').not(this).removeClass('active');
        $('.panel').not($(this).next('.panel')).slideUp();
      });
    });
  </script>
</body>
</html>

在上述代码中,我们使用了jQuery的click事件来监听点击事件。当点击某个accordion按钮时,我们首先切换该按钮的active类,然后使用slideToggle方法来切换该按钮对应的panel的显示和隐藏。

为了实现关闭其他打开的div的功能,我们使用了.not()方法来排除当前点击的按钮和对应的panel,然后分别移除其他按钮的active类,并使用slideUp方法来隐藏其他panel

这样,当我们点击某个按钮时,该按钮对应的panel会展开或收起,同时其他已展开的panel会被关闭。

这个功能在一些常见的折叠面板、手风琴菜单等场景中经常使用。腾讯云提供了丰富的云计算产品,例如云服务器、云数据库、云存储等,可以根据具体需求选择适合的产品。具体产品介绍和相关链接可以参考腾讯云官方网站:https://cloud.tencent.com/

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的结果

领券