用jquery写一个双层选项卡

博主:adminadmin 2023-08-23 928 0条评论
温馨提示:文章已超过218天没有更新,若内容或图片失效,请留言反馈!
摘要: <!DOCTYPE html><html>  <head>   <style>   ...

<!DOCTYPE html>

<html>

  <head>

   <style>
   .tabs {
  width: 400px;
}
.tab-header {
  display: flex;
}
.tab-item {
  padding: 10px;
  background-color: #ccc;
  cursor: pointer;
}
.tab-item.active {
  background-color: #f00;
  color: #fff;
}
.tab-pane {
  display: none;
  padding: 20px;
  background-color: #f0f0f0;
}
.tab-pane.active {
  display: block;
}
   </style>

  </head>

  <body>

    <div class="tabs">
  <div class="tab-header">
    <div class="tab-item active">选项1</div>
    <div class="tab-item">选项2</div>
    <div class="tab-item">选项3</div>
  </div>
  <div class="tab-content">
    <div class="tab-pane active">内容1</div>
    <div class="tab-pane">内容2</div>
    <div class="tab-pane">内容3</div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>

<script>
$(document).ready(function() {
  // 默认显示第一个选项卡
  $(".tab-header .tab-item:first").addClass("active");
  $(".tab-content .tab-pane:first").addClass("active");
  // 点击选项卡切换内容
  $(".tab-header .tab-item").click(function() {
    var index = $(this).index();
    // 切换选项卡
    $(".tab-header .tab-item").removeClass("active");
    $(this).addClass("active");
    // 切换内容
    $(".tab-content .tab-pane").removeClass("active");
    $(".tab-content .tab-pane:eq(" + index + ")").addClass("active");
  });
});
</script>

  </body>

</html>

110.png

分享