我正在尝试创建一个可以通过简单的滑出动画展开和折叠的框。如果您运行下面的示例,其想法是它以一条红线开始,当您单击按钮时,它会分成两条读取线并轻轻展开以显示内容,就像从表格中拉出画一样。
我已经尝试了转换、动画、相对:使用顶部定位,但无法获得所需的效果。
包含框的大小应扩大
function expandContract() {
const el = document.getElementById("expand-contract")
el.classList.toggle('expanded')
el.classList.toggle('collapsed')
}Run Code Online (Sandbox Code Playgroud)
#container {
border: 1px solid black;
padding: 15px;
}
#top-section {
border-bottom: 1px solid red;
}
#expand-contract {
border-bottom: 1px solid red;
}
.expand-contract {
transform: translateY(-100%)
overflow: hidden;
}
@keyframes slide-in {
100% {
transform: translateY(0%)
}
}
.expanded {
background-color: green;
animation-name: slide-in;
animation-duration: 1s;
}
.collapsed {
background-color: red;
transform: translateY(-100%)
}Run Code Online (Sandbox Code Playgroud)
<div id="container">
<div id="top-section">
This is always displayed
</div>
<div id="expand-contract" class="expanded">
This section expands and contracts
<table>
<tr><td>test1</td></tr>
<tr><td>test2</td></tr>
<tr><td>test3</td></tr>
<tr><td>test4</td></tr>
</table>
</div>
<div id="bottom-section">
This section is always displayed
</div>
</div>
<button onclick="expandContract()">Expand/Contract</button>Run Code Online (Sandbox Code Playgroud)
您可以使用 CSStransition和切换样式来实现这一点。最初您可能会考虑转换高度(从0到initial以便它根据高度动态扩展),但不幸的是 CSStransition没有正确处理这个问题。
相反,您可以将其包装在自己的容器中overflow: hidden,然后使用 amargin-top: -100%将其隐藏和0显示。
这是您进行此修改的代码:
function expandContract() {
const el = document.getElementById("expand-contract")
el.classList.toggle('expanded')
el.classList.toggle('collapsed')
}Run Code Online (Sandbox Code Playgroud)
#container {
border: 1px solid black;
padding: 15px;
}
#top-section {
border-bottom: 1px solid red;
}
#expand-container {
overflow: hidden;
}
#expand-contract {
border-bottom: 1px solid red;
margin-top: -100%;
transition: all 1s;
}
#expand-contract.expanded {
background-color: green;
margin-top: 0;
}Run Code Online (Sandbox Code Playgroud)
<div id="container">
<div id="top-section">
This is always displayed
</div>
<div id="expand-container">
<div id="expand-contract" class="expanded">
This section expands and contracts
<table>
<tr><td>test1</td></tr>
<tr><td>test2</td></tr>
<tr><td>test3</td></tr>
<tr><td>test4</td></tr>
</table>
</div>
</div>
<div id="bottom-section">
This section is always displayed
</div>
</div>
<button onclick="expandContract()">Expand/Contract</button>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12686 次 |
| 最近记录: |