使用CSS最大高度过渡向上/向下滑动?

时间:2016-02-12 17:56:38

标签: html css css3

我正在开发一种手风琴滑块,它有几个标签,然后是一个内容块,点击标签标题后会向下滑动。我本来打算使用jQuery slideToggle()来实现这个目标,但它非常不稳定所以我决定尝试一种仅用于CSS的方法。

我发现大多数关于在CSS中执行此操作的文章建议使用max-height:0和max-height:9999px并使用过渡到动画。问题是,当我设置max-height:0时,看起来填充仍然显示并且内容也显示出来。如何调整此选项以隐藏整个下拉内容框,然后向下滑动?

$(function() {
	$('.dropdown-title').click(function() {
  	$(this).parent().toggleClass('active');
  });
});
.dropdown-item {
	border:1px solid black;
}
	.dropdown-title {
		font-size:36px;
		padding:15px 30px;
		position:relative;
		cursor:pointer;
	}
    .dropdown-item.active .dropdown-title {
      background:#000;
      color:#fff;
    }
	.dropdown-content {
		max-height:0;
		padding:35px 30px;
        transition:max-height 0.5s;
	}
    .dropdown-item.active .dropdown-content {
      max-height:9999px;
    }
		.dropdown-content p strong:first-child {
			font-size:20px;
		}
		.dropdown-content p {
			padding-bottom:0;
			padding-top:25px;
			margin-bottom:0;
		}
			.dropdown-content p:first-child {
				padding-top:0;
			}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown-container">
  <div class="dropdown-item">
    <div class="dropdown-title">Lorem Ipsum</div>
    <div class="dropdown-content">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur in sapien in nibh venenatis pulvinar nec at lorem. In eget imperdiet dolor. Nullam non volutpat quam. In vel quam mi. Sed non iaculis enim. Proin eu felis vulputate, maximus elit et, semper urna. Pellentesque massa urna, lobortis vitae iaculis sed, convallis ut turpis. Vivamus quis euismod nisi.
      </p>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur in sapien in nibh venenatis pulvinar nec at lorem. In eget imperdiet dolor. Nullam non volutpat quam. In vel quam mi. Sed non iaculis enim. Proin eu felis vulputate, maximus elit et, semper urna. Pellentesque massa urna, lobortis vitae iaculis sed, convallis ut turpis. Vivamus quis euismod nisi.
      </p>
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur in sapien in nibh venenatis pulvinar nec at lorem. In eget imperdiet dolor. Nullam non volutpat quam. In vel quam mi. Sed non iaculis enim. Proin eu felis vulputate, maximus elit et, semper urna. Pellentesque massa urna, lobortis vitae iaculis sed, convallis ut turpis. Vivamus quis euismod nisi.
      </p>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:1)

您需要overflow: hidden内容,并将填充文件移动到活动状态。

.dropdown-content {
    max-height: 0;
    transition: max-height 0.5s;
    overflow: hidden;
}

.dropdown-item.active .dropdown-content {
   max-height:9999px;
   padding: 35px 30px;
}