我希望能够显示一个带有一个补间动画的元素,并通过单击相同的按钮隐藏不同的动画。我尝试切换.active类并根据box是否具有类来有条件地显示或隐藏。我只有一次工作。我想知道如何做到这一点(仍然使用香草js),以及我如何搞砸了。
const btn = document.querySelector('.btn');
const box = document.querySelector('.box');
const showBox = new TimelineMax({paused: true});
//alias for brevity
const sb = showBox;
const hb = new TimelineMax({paused: true}); //hidebox
btn.addEventListener('click', function(){
if(box.classList.contains('active') !== true) {
sb.play();
sb.set(box, {opacity: 0, y: 0});
sb.fromTo(box, 0.5, {opacity: 0, y: 0}, {opacity: 1, y: 0});
box.classList.add('active');
}
else if(box.classList.contains('active')) {
hb.play();
hb.fromTo(box, 0.5, {opacity: 1, y: 0}, {opacity: 0, y: -100});
box.classList.remove('active');
}
});
.box {
width: 100px;
height: 100px;
background-color: blue;
opacity: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.1/TweenMax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.0.1/TimelineMax.min.js"></script>
<button class="btn">Show / Hide</button>
<br><br>
<div class="box"></div>