纯CSS实现页面中的列表收拉效果

来自:互联网
时间:2021-03-03
阅读:

你可能经常见到下面这样的效果:

纯CSS实现页面中的列表收拉效果

没错,就是页面上常用的“展开收起”交互形式,通常的做法就是控制display属性值在none和其他值之间切换,但是虽说功能可以实现,效果却非常生硬,所以就会有这样的一个需求 —— 希望元素在展开收起时能够有明显的高度滑动效果。

以前的实现可以用jQuery的slideUp()/slideDown()方法,但是,在移动端,因为CSS3动画支持良好,所以移动端的JavaScript框架都是没有提供动画模块的。这里自然而然就想到了CSS3技术。


笔者的第一反应就是用height+overflow:hidden;实现,既没有性能问题,也不必担心显示问题。但是转眼间就想到:很多时候我们需要展现的内容都是动态的,也就是说内容高度是不固定的(当然,你也可以用overflow-y:auto; 暂且不论)。而要达到这种效果,height就要使用“非固定值auto”!

但是auto并不是数值,而是一个关键字,所以在一个隐性规定 —— 数值和关键字之间无法计算 下,如果我们使用height0pxauto之间切换,是无法形成过渡或动画效果的。

同样的还有css中的clip-path属性:很多初学者习惯于在none和具体值之间形成动画效果,这是不可能的。

因此,想要达到文首的效果,笔者推荐max-height属性:

<div class="accordion">
	<input id="collapse1" type="radio" name="tap-input" hidden />
	<input id="collapse2" type="radio" name="tap-input" hidden />
	<input id="collapse3" type="radio" name="tap-input" hidden />
	<article>
		<label for="collapse1">列表1</label>
		<p>内容1<br>内容2<br>内容3<br>内容4</p>
	</article>
	<article>
		<label for="collapse2">列表2</label>
		<p>内容1<br>内容2<br>内容3<br>内容4</p>
	</article>
	<article>
		<label for="collapse3">列表3</label>
		<p>内容1<br>内容2<br>内容3<br>内容4</p>
	</article>
</div>
.accordion {
	width: 300px;
}
.accordion article {
	cursor: pointer;
}
label {
	display: block;
	padding: 0 20px;
	height: 40px;
	background-color: #f66;
	cursor: pointer;
	line-height: 40px;
	font-size: 16px;
	color: #fff;
}
p {
	overflow: hidden;
	padding: 0 20px;
	margin: 0;
	border: 1px solid #f66;
	border-top: none;
	border-bottom-width: 0;
	max-height: 0;
	line-height: 30px;
	transition: all .5s ease;
}
input:nth-child(1):checked ~ article:nth-of-type(1) p,
input:nth-child(2):checked ~ article:nth-of-type(2) p,
input:nth-child(3):checked ~ article:nth-of-type(3) p {
	border-bottom-width: 1px;
	max-height: 130px;
}

在css中,min-height/max-height出现的场景一定是自适应布局或者流体布局中。而对于展开后的max-height值,我们只需要保证设定值比内容高度大即可 —— 因为在max-height > height 时,元素高度就会以height属性的高度计算

但是建议不要把max-height值设置的太大,毕竟transition或animation的时间是“完成动画的时间”而不是“内容展示出来的时间”


收拉效果还有一种展现形式:

纯CSS实现页面中的列表收拉效果

其特点是鼠标悬浮到组件的某个部分,该部分就会扩张开来并挤压旁边的部分,当鼠标离开时就恢复原状。若鼠标快速在其上面略过,就会产生手风琴弹琴的效果。

使用JS实现手风琴效果,必须监听mouseentermouseleave两个鼠标事件,而CSS中的:hover可代替两者的效果。所以纯CSS实现手风琴效果的关键就是:hover ,其核心代码如下:

li {
}
li:hover {
}

而对布局来说,这种以相同/不同宽度排列在一排的元素想要实现在一行内的展开收缩效果,比较好的方式就是 flex

<ul class="accordion">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>
.accordion {
	display: flex;
	width: 600px;
	height: 200px;
}
li {
	flex: 1;
	cursor: pointer;
	transition: all 300ms;
}
li:nth-child(1) {
	background-color: #f66;
}
li:nth-child(2) {
	background-color: #66f;
}
li:nth-child(3) {
	background-color: #f90;
}
li:nth-child(4) {
	background-color: #09f;
}
li:nth-child(5) {
	background-color: #9c3;
}
li:nth-child(6) {
	background-color: #3c9;
}
li:hover {
	flex: 2;
	background-color: #ccc;
}

这里有一点值得注意:像有些“特殊”情况比如 animation 的延迟,可以以 内联style 的方式在HTML中插入 CSS自定义变量 ,可以简洁代码:从一次项目重构说起CSS3自定义变量在项目中是如何使用的?

返回顶部
顶部