首页 > 解决方案 > SlideToggle 列表关闭时仅显示列表的一部分

问题描述

我有一长串项目
我只想默认显示其中的一部分
并在按钮单击时显示所有项目

我有这个jsfiddle,但是如何使用 jQuery slideToggle() 对其进行动画处理:

HTML:

<ul class="faded part">
  <li>List item</li>    
  <li>List item</li>
  <li>List item</li>
  <li>List item</li>
  <li>List item</li>
</ul>
<button class="expand">Open</button>

CSS:

.part li:nth-of-type(-n+3) {
  display: inherit !important;
}    
.part li {
  display: none;
}     

JS:

$(document).ready(function() {
  $(".expand").click(function() {
    if ($(this).text() != "Close") {
      $(this).parent().children("ul").removeClass("part");
      $(this).text("Close");
    } else {
      $(this).parent().children("ul").addClass("part");
      $(this).text("Open");
    }
  });
});

标签: jqueryhtml

解决方案


你可以尝试这样的事情。

检查链接以获取更多信息。

$(document).ready(function() {

  $(".expand").click(function() {
    if ($(this).text() != "Close") {
      $(this).parent().children("ul").removeClass("closed");
      $(this).text("Close");
      
    } else {
      $(this).parent().children("ul").addClass("closed");
      $(this).text("Open");
    }
  });
});
li {
  display: inherit;
}

.slider.closed {
	max-height: 20px;
}

.slider {
	overflow-y: hidden;
	max-height: 500px; /* approximate max height */

	transition-property: all;
	transition-duration: .5s;
	transition-timing-function: cubic-bezier(0, 1, 0.5, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="slider closed">
  <li>List item</li>
  <li>List item</li>
  <li>List item</li>
  <li>List item</li>
  <li>List item</li>
  <li>List item</li>
  <li>List item</li>
  <li>List item</li>
  <li>List item</li>
</ul>
<button class="expand">Open</button>


推荐阅读