[英]How to make a slide(up/down) without jQuery?
我正在尝试为我的折叠组件(如引导程序)制作一个滑动(上/下)系统,但我无法获得要动画的元素的高度(没有高度,我认为无法为元素设置动画-如果这是错误的,那么我如何为元素设置动画?)!
注意: [我想使用纯 javascript]
document.getElementById('btn').addEventListener('click', function(){ this.nextElementSibling.classList.toggle('active'); })
body{ font-family: Segoe UI; font-size: 1rem; line-height: 1.5; } .collapse{ border: 1px solid #e7e7e7; border-radius: .25rem; overflow: hidden; } #btn{ padding: .75rem 1.25rem; width: 100%; border: none; font-size: inherit; background-color: #fff; cursor: pointer; } #btn:focus{ outline: 0; } .collapse-content{ font-size: 95%; padding: .75rem .75rem; display: none; } .collapse-content.active{ display: block; }
<div class="collapse"> <button id="btn"> Click Me </button> <div class="collapse-content"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Mollitia ut explicabo nesciunt minima pariatur saepe eveniet officia ducimus perferendis suscipit? </div> </div>
可以通过对标记进行一些小的更改来实现将考虑任何内部高度(具有一致的过渡速度)的基本原版 JavaScript 实现。
<div class="collapse">
<button id="btn"> Click Me </button>
<div class="collapse-wrapper">
<div class="collapse-content">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Mollitia ut explicabo nesciunt minima pariatur saepe eveniet officia ducimus perferendis suscipit?
</div>
</div>
</div>
请注意添加了collapse-wrapper
div。 这将允许您渲染内容并测量其高度,而无需实际显示内容。 那么这只是在点击时显示/隐藏内容的一个简单案例:
* {
box-sizing: border-box;
}
.collapse-wrapper {
overflow: hidden;
transition: all 300ms ease-in;
}
const wrapper = document.querySelector('.collapse-wrapper')
const content = document.querySelector('.collapse-content')
const button = document.getElementById('btn')
let open = true
// Set initial height to content height, if shown by default
if (open) {
wrapper.style.height = `${content.getBoundingClientRect().height}px`
}
function toggleOpen () {
if (open) {
wrapper.style.height = '0px'
open = false
} else {
const height = content.getBoundingClientRect().height
wrapper.style.height = `${height}px`;
open = true
}
}
button.addEventListener('click', toggleOpen)
您需要使用max-height
。 是的,这很糟糕,因为这意味着您需要设置一些任意的最大高度,如果内容增长,稍后可能需要调整该高度。 但是,在这种情况下您不能为高度设置动画,因为在内容打开之前未定义高度。
就像是:
.collapse-content{
font-size: 95%;
padding: .75rem .75rem;
max-height: 0;
transition: max-height .3s;
}
.collapse-content.active{
max-height: 200px; //something bigger than what you need
}
function slide(){ document.getElementById("sliding").style.maxHeight = "1000px"; }
#sliding{ transition: 0.5s; max-height: 0px; overflow: hidden; }
<button onclick ="slide();">Slide it</button> <div id = "sliding"> <h1>It works</h1> <p>Hello there</p> </div>
这有点棘手,因为您必须将 maxHeight 设置为您认为您的内容将获得的最大高度。
来源: 我如何过渡高度:0; 到高度:自动; 使用CSS?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.