https://jsfiddle.net/elgs/580nhepk/11/
这个小小的演示尝试使用tableView
计时/缓动功能向上/向下滑动div。然而,似乎缓和效果仅在第一次滑落时才有效。从第二次开始,宽松效应似乎消失了。
HTML
ease-in
的Javascript
<button id='slideup'>Slide Up</button>
<button id='slidedown'>Slide Down</button>
<div id="a"></div>
CSS
const a = document.querySelector('div#a');
const u = document.querySelector('button#slideup');
const d = document.querySelector('button#slidedown');
u.addEventListener('click', (e) => {
a.style.setProperty('--height', '30px');
a.classList.add('slide');
});
d.addEventListener('click', (e) => {
a.style.setProperty('--height', '100px');
a.classList.add('slide');
});
答案 0 :(得分:2)
这是因为你已经将动画设置为只运行一次,所以它不会再次运行,除非你每次从元素中删除动画类+触发重排+更新其高度 property。
const a = document.querySelector('div#a');
const u = document.querySelector('button#slideup');
const d = document.querySelector('button#slidedown');
u.addEventListener('click', (e) => {
a.style.setProperty('height', '100px'); // so the animation knows the 'from' value
a.style.setProperty('--height', '30px');
a.classList.remove('slide'); // so the animation starts again
a.offsetHeight; // so the no-class be calculated
a.classList.add('slide');
});
d.addEventListener('click', (e) => {
a.style.setProperty('height', '30px');
a.style.setProperty('--height', '100px');
a.classList.remove('slide');
a.offsetHeight;
a.classList.add('slide');
});
div#a {
width: 100px;
height: 100px;
box-sizing: border-box;
border: 1px solid gray;
}
@keyframes slide {
to {
height: var(--height);
}
}
.slide {
animation-name: slide;
animation-duration: .4s;
animation-timing-function: ease-in;
animation-delay: 0s;
animation-direction: normal;
animation-iteration-count: 1;
animation-fill-mode: forwards;
animation-play-state: running;
}
<button id='slideup'>Slide Up</button>
<button id='slidedown'>Slide Down</button>
<div id="a"></div>
但无论如何,你想要的不是动画而是过渡:
const a = document.querySelector('div#a');
const u = document.querySelector('button#slideup');
const d = document.querySelector('button#slidedown');
u.addEventListener('click', (e) => {
a.style.setProperty('--height', '30px');
});
d.addEventListener('click', (e) => {
a.style.setProperty('--height', '100px');
});
div#a {
width: 100px;
height: 100px;
height: var(--height, 100px);
box-sizing: border-box;
border: 1px solid gray;
}
.slide {
transition: height .4s ease-in;
}
<button id='slideup'>Slide Up</button>
<button id='slidedown'>Slide Down</button>
<div id="a" class="slide"></div>
答案 1 :(得分:0)
css动画在页面加载时第一次执行动画。 在这种情况下,您应该使用css transition而不是css animation 例如:
.slide-up {
height : 30px;
}
.slide-down {
height : 60px;
}
#a{
transition: height 200ms
}