我正在实现一个具有一些隐藏内容的组件,只需单击一下按钮即可显示出来。我想对显示内容的max-height
进行过渡,例如:
<button id="show-hide">Toggle content</button>
<div id="revealable-content" class="content is-collapsed">
Content to be revealed
<a href="https://www.example.com">with a link</a>
</div>
.content {
overflow: hidden;
height: auto;
max-height: 200px;
width: 200px;
background-color: darkgray;
transition: max-height 1000ms;
}
.content.is-collapsed {
max-height: 0
}
const button = document.getElementById('show-hide')
const content = document.getElementById('revealable-content')
let hidden = true
button.addEventListener('click', () => {
hidden = !hidden
if (hidden) {
content.classList.add('is-collapsed')
} else {
content.classList.remove('is-collapsed')
}
})
到目前为止,一切都很好。现在,我想使它更易于访问,因此我向内容div添加了hidden
属性,并在我知道使用setTimeout
执行动画后将其设置为true或false。
// at the bottom of the event handler... setTimeout(() => { content.hidden = hidden }, 1000)
这会破坏“扩展”动画,但奇怪的是不会破坏“崩溃”动画。折叠时,过渡动画将按预期运行1秒钟。但是在展开时,
max-height
立即应用,没有过渡。
请参见this codepen以获取演示。
发生了什么,如何解决?
我正在实现一个具有一些隐藏内容的组件,只需单击一下按钮即可显示出来。我想对显示内容的最大高度进行过渡,例如:
hidden
属性的元素具有这样的浏览器porpertis:height: auto;
没有动画效果,但是height属性。但是,当您的元素被隐藏(display: none)
时,您将无法获得高度。因此,您需要克隆它并获取高度,然后可以使用该高度应用动画。充分了解此[Q-A]
<!DOCTYPE html>
<html>
<head>
<title>Avinash</title>
<style>
#slider {
margin:0px auto;
padding:0px;
width:400px;
border:1px solid #000;
background:#0f0;
height:20px;
overflow:hidden;
}
</style>
<script>
var minheight = 20;
var maxheight = 300;
var time = 1000;
var timer = null;
var toggled = false;
window.onload = function() {
var controler = document.getElementById('slide');
var slider = document.getElementById('slider');
slider.style.height = minheight + 'px';
controler.onclick = function() {
clearInterval(timer);
var instanceheight = parseInt(slider.style.height);
var init = (new Date()).getTime();
var height = (toggled = !toggled) ? maxheight: minheight;
var disp = height - parseInt(slider.style.height);
timer = setInterval(function() {
var instance = (new Date()).getTime() - init;
if(instance < time ) {
var pos = Math.floor(disp * instance / time);
result = instanceheight + pos;
slider.style.height = result + 'px';
document.getElementById('log').innerHTML = 'Current Height : <b>' + result + '</b><br /> Current Time : <b>' + instance + '</b>';
}else {
slider.style.height = height + 'px'; //safety side ^^
clearInterval(timer);
controler.value = toggled ? ' Slide Up ' :' Slide Down ';
document.getElementById('log').innerHTML = 'Current Height : <b>' + height + '</b><br /> Current Time : <b>' + time + '</b>';
}
},1);
};
};
</script>
</head>
<body>
<h1> Toggle Slide </h1>
<input type="button" id="slide" value =" Slide Down "/>
<span id="log" style="position:absolute; left:10px; top:150px;"></span>
<br />
<div id="slider">
content goes here
</div>
</body>
</html>