转载地址:/u/4369742/blog/3484647
HTML代码:
<div
className={CX('font-size-selector-sub-list', {
show: shouldSubListShow === true,
hidden: shouldSubListShow === false,
})}
>
{
((item, index) => {
return (
<div
role="button"
tabIndex={0}
key={item}
className="font-size-selector-sub-items"
onClick={() => { handleClickSubItem(index) }}
>
<div className="font-size-selector-span">{item}</div>
</div>
)
})
}
</div>
CSS代码:
@keyframes slide-down{
0%{transform:scale(1,0);}
100%{transform:scale(1,1);}
}
@-webkit-keyframes slide-down{
0%{-webkit-transform:scale(1,0);}
100%{-webkit-transform:scale(1,1);}
}
.font-size-selector-sub-list {
position: absolute;
top: 21px;
left: 0;
width: 100%;
box-sizing: border-box;
z-index: 1;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.5);
background-color: #ffffff;
border-radius: 2px;
cursor: pointer;
.font-size-selector-sub-items {
padding: 0 6px;
height: 19px;
box-sizing: border-box;
background-color: #ffffff;
background-repeat: no-repeat;
display: flex;
justify-content: space-between;
align-items: center;
&:hover {
background-color: #d3edfb;
}
}
}
.show {
max-height: 114px;
transition: max-height .3s ease-in;
transform-origin: 50% 0;
animation: slide-down 0.3s ease-in;
-webkit-animation: slide-down 0.3s ease-in;
}
.hidden {
max-height: 0px;
overflow: auto;
transition: max-height .3s ease-out;
}
注意点:
1,自上而下展开效果:transition与animation结合使用。如上:.show
2,自下而上收起效果:transition单独使用。如上:.hidden
首先想到的是在收起和展开两个终点位置改变 max-height,然后均加上transition,但是这样做只能实现下拉框父元素收起和展开,内部子元素高度变不了,所以想到加上overflow:auto/hidden,但是这样又只能对收起起作用,展开无作用,原因是,展开时子元素内容高度小于等于父元素展开时设置的max-height,所以针对展开,需要使用transform:scale();属性,这样可以在展开时,让子元素内容慢慢缩放至父元素的高度。需要注意的是,缩放时要设置 transform-origin: 50% 0;分别表示x,y开始缩放位置。