获得最接近的课程fadeIn on click和sibling to fadeOut

时间:2017-05-12 18:05:08

标签: javascript jquery fadein closest

我正试图像菜单一样切换显示不同的信息,但我的尝试不起作用。

我要找的是如果用户点击任何标题(A,B或C),说明将fadeIn。这就是我尝试使用closest()方法获取与标题相关的描述的原因。然后当用户点击不同的标题时,关闭当前的标题,然后打开另一个标题。

有人看到我做错了吗?

$(".service-list-title").on("click", function(event) {
  $(this).closest('.service-list-description').fadeIn(300).siblings().closest('.service-list-description').fadeOut(300);
});
.service-list-title {
  display: block;
  color: #333333;
  font-size: 1.1rem;
  letter-spacing: .1rem;
  margin: 20px 0px;
  padding: 0 10px 0 25px;
  cursor: pointer;
  transition: all .35s ease;
  -webkit-transition: all .35s ease;
}

.service-list-description {
  display: none;
  color: #333333;
  font-size: .9rem;
  margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="service-list">
  <li class="service-list-title">A</li>
  <p class="service-list-description">This is the content for A</p>
</div>
<div class="service-list">
  <li class="service-list-title">B</li>
  <p class="service-list-description">This is the content for B</p>
</div>
<div class="service-list">
  <li class="service-list-title">C</li>
  <p class="service-list-description">This is the content for C</p>
</div>

2 个答案:

答案 0 :(得分:1)

以下功能可以满足您的要求:

$(".service-list-title").on("click", function(event) {
  $('.service-list-description').fadeOut(300); // Close any that's open
  $(this).siblings('.service-list-description').fadeIn(300); // Open new
});

小提琴:https://jsfiddle.net/beekvang/oro9ue3k/

答案 1 :(得分:1)

您的代码存在的问题是,您使用closest()来查找父元素,而不是next()siblings()来搜索同一级别的元素。

但是,通过将事件处理程序附加到.service-list元素并使用find()将所需元素添加到fadeToggle(),您可以使逻辑更简单。然后,您可以选择所有其他.service-list-description元素,并调用fadeOut()来隐藏它们。试试这个:

$(".service-list").on("click", function(event) {
  var $target = $(this).find('.service-list-description').fadeToggle(300);
  $('.service-list-description').not($target).fadeOut(300);
});
.service-list-title {
  display: block;
  color: #333333;
  font-size: 1.1rem;
  letter-spacing: .1rem;
  margin: 20px 0px;
  padding: 0 10px 0 25px;
  cursor: pointer;
  transition: all .35s ease;
  -webkit-transition: all .35s ease;
}

.service-list-description {
  display: none;
  color: #333333;
  font-size: .9rem;
  margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="service-list">
  <li class="service-list-title">A</li>
  <p class="service-list-description">This is the content for A</p>
</div>
<div class="service-list">
  <li class="service-list-title">B</li>
  <p class="service-list-description">This is the content for B</p>
</div>
<div class="service-list">
  <li class="service-list-title">C</li>
  <p class="service-list-description">This is the content for C</p>
</div>