首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将平滑替换添加到网格容器中的div?

如何将平滑替换添加到网格容器中的div?
EN

Stack Overflow用户
提问于 2021-02-17 06:57:37
回答 1查看 42关注 0票数 0

FIRST Run the script below to understand what I'm talking about here

我们现在所拥有的

我们有一个盒子和一个容器。

2秒后,它开始从位置1移动到位置2。

js代码基本上更改了框的grid-column属性以替换它。

问题

我怎么才能让它的运动更流畅一点呢?比如,transition: all 1s不能工作。有什么想法吗?

代码语言:javascript
复制
setTimeout( () => {
    const box = document.getElementById("box");
    

    box.classList.remove("pos-1");
    
    box.classList.add("pos-2");
    
  
}, 2000);
代码语言:javascript
复制
.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;
  
}
代码语言:javascript
复制
<div class="container">
  <span class="pos-1" id="box"></span>
</div>

EN

回答 1

Stack Overflow用户

发布于 2021-02-17 08:11:24

我不知道像你想要的那样使用网格元素来做这件事,但是你可以使用CSS动画,并使用@keyframe得到一个很好的补间动画。然后使用JS使用setTimeout将元素设置在关键帧末尾的位置。我还使用根元素来发送变量,因此所有内容都在相同的持续时间内。条件将两秒的超时2000拆分为2s,并将其发送到根元素,以便在CSS动画持续时间内使用。

代码语言:javascript
复制
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);
代码语言:javascript
复制
.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));
  }
}
代码语言:javascript
复制
<div class="container">
  <span id="box"></span>
</div>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66233359

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档