[英]How to make button slide with animated collapsible div?
I have a div which collapses on a button click.我有一个在单击按钮时折叠的 div。 Code as follows:
代码如下:
const collapse = () => { const title = document.getElementById('title'); title.classList.add('d-none'); const out = document.getElementById('out'); out.classList.add('collapse'); }
.out { width: 200px; background-color: grey; display: flex; justify-content: space-between; }.d-none { display: none; }.collapse { width: 65px; }.btn { width: 65px; }
<div id='out' class='out'> <span id='title'>Title</span> <button class='btn' onclick='collapse()'>Collapse</button> </div>
I'd like to add a transition effect, so that the div would collapse smoothly, the button would move smoothly to the left end with div collapse.我想添加一个过渡效果,让 div 平滑折叠,按钮平滑移动到 div 折叠的左端。 How can I do that?
我怎样才能做到这一点?
EDIT I may have misunderstood what your intended outcome is.编辑我可能误解了您的预期结果。 If you comment on here what you'd like it to do, I can make it more correctly align.:)
如果你在这里评论你想要它做什么,我可以让它更正确地对齐。:)
I've added an example with what you have, but I'd recommend just adding and removing a class based on the state.我已经添加了一个示例,但我建议您仅添加和删除基于 state 的 class。
Basically, you just toggle the 'collapse' classname, and add transition
properties to the div class, as well as the collapse class.基本上,您只需切换“折叠”类名,并将
transition
属性添加到 div class 和折叠 class。 You can see the code below:你可以看到下面的代码:
const collapse = () => { const out = document.getElementById('out'); // We only have to toggle the collapse class out.classList.toggle('collapse'); }
.out { width: 200px; background-color: grey; display: inline-block; /* This transition happens when the collapse is removed */ transition: all 300ms ease-in-out; }.d-none { height: 0; }.collapse { width: 0; /* This transition happens when the collapse class is added */ transition: all 300ms ease-in-out; }.btn { width: auto; margin-left: -5px; }
<div id='out' class='out'> <span id='title'>Title</span> </div> <button class='btn' onclick='collapse()'>Collapse</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.