jquery 如果类具有活动的类,则显示不同的元素

egdjgwm8  于 2023-06-22  发布在  jQuery
关注(0)|答案(1)|浏览(120)

Summary我使用carousel作为导航。

<div class="swiper-slide state1 swiper-slide-active">STATE 1</div>

<div class="swiper-slide state2 ">STATE 2</div>

<p class="state1-content">state 1</p>

<p class="state2-content">state 2</p>

.state2-content {
  display:none;
}

<script>
  jQuery(".grad-nav .swiper-slide").addClass(function (i) {
    return 'state' + (i + 1)
 });
 if (jQuery(".state1").hasClass("swiper-slide-active")) {
   jQuery(".state1-content").fadeIn(300);
   jQuery(".state2-content").fadeOut(300);
 }

 if (jQuery(".state2").hasClass("swiper-slide-active")) {
    jQuery(".state2-content").fadeIn(300);
 jQuery(".state1-content").fadeOut(300);
 }
</script>

总结请帮帮我。

我想显示其他元素,如果类检测到它有类活动。

55ooxyrt

55ooxyrt1#

使用if else条件不是多个元素的通用方式。因此,以下代码在您的情况下工作正常:

CSS

<style>
    .state2-content {
         display:none;
    }
</style>

HTML

<div class="swiper-slide state1 swiper-slide-active">STATE 1</div>
<div class="swiper-slide state2">STATE 2</div>
<p class="state1-content">state 1</p>
<p class="-content">state 2</p>

脚本

<script>
  $(document).ready(function() {
    $(".grad-nav .swiper-slide").addClass(function (index) {
      return 'state' + (index + 1);
    });

    $(".grad-nav .swiper-slide").on('click', function() {
      var activeState = $(this).attr('class').split(' ')[1];
      $(".grad-nav .state-content").fadeOut(300);
      $("." + activeState + "-content").fadeIn(300);
    });
  });
</script>
$(document).ready(function() {
    $(".grad-nav .swiper-slide").addClass(function (index) {
      return 'state' + (index + 1);
    });

    $(".grad-nav .swiper-slide").on('click', function() {
      var activeState = $(this).attr('class').split(' ')[1];
      $(".grad-nav .state-content").fadeOut(300);
      $("." + activeState + "-content").fadeIn(300);
    });
  });
.state2-content {
        display:none;
    }
<div class="swiper-slide state1 swiper-slide-active">STATE 1</div>
<div class="swiper-slide state2">STATE 2</div>
<p class="state1-content">state 1</p>
<p class="state2-content">state 2</p>

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

相关问题