FIRST Run the script below to understand what I'm talking about here
我们现在所拥有的
我们有一个盒子和一个容器。
2秒后,它开始从位置1移动到位置2。
js代码基本上更改了框的grid-column属性以替换它。
问题
我怎么才能让它的运动更流畅一点呢?比如,transition: all 1s不能工作。有什么想法吗?
setTimeout( () => {
const box = document.getElementById("box");
box.classList.remove("pos-1");
box.classList.add("pos-2");
}, 2000);.container {
width: 300px;
height: 300px;
display: grid;
grid-template-columns: repeat(6, 1fr);
grid-template-rows: repeat(6, 1fr);
}
#box {
background-color: red
}
.pos-1 {
grid-column: 1;
}
.pos-2 {
grid-column: 4;
}<div class="container">
<span class="pos-1" id="box"></span>
</div>
发布于 2021-02-17 08:11:24
我不知道像你想要的那样使用网格元素来做这件事,但是你可以使用CSS动画,并使用@keyframe得到一个很好的补间动画。然后使用JS使用setTimeout将元素设置在关键帧末尾的位置。我还使用根元素来发送变量,因此所有内容都在相同的持续时间内。条件将两秒的超时2000拆分为2s,并将其发送到根元素,以便在CSS动画持续时间内使用。
const root = document.documentElement; //--> <html> element
const box = document.getElementById("box");
const distance = `150px`;
const duration = 2000;
const move = (distance, duration) => {
// the conditional makes sure the setTimeout time and duration time in the css are the same
// transform the duration into proper seconds for the CSS animations on the CSS side
if (`${duration}`.length > 3) {
let whole = `${duration}`.slice(0, `${duration}`.length - 3);
root.style.setProperty('--duration', `${whole}s`);
} else { // this is milliseconds send over as is
root.style.setProperty('--duration', `.${duration}s`);
}
// send the distance over to the root element (HTML) and
// transfer to target element using a css variable in css
root.style.setProperty('--distance', distance);
// timeout to set the elements position at the end of the keyframe tween
setTimeout(() => {
box.style.transform = `translateX(${distance})`;
}, duration + 10);
}
move(distance, duration);.container {
width: 300px;
height: 300px;
display: grid;
grid-template-columns: repeat(6, 1fr);
grid-template-rows: repeat(6, 1fr);
position: relative;
}
#box {
background-color: red;
width: 50px;
height: 50px;
animation: moveToRight var(--duration) ease-in-out;
animation-delay: 2s;
}
@keyframes moveToRight {
0% {
transform: translateX(0px);
}
100% {
transform: translateX(var(--distance));
}
}<div class="container">
<span id="box"></span>
</div>
https://stackoverflow.com/questions/66233359
复制相似问题