有没有一种方法可以将元素从一个网格移动到另一个网格

时间:2020-08-11 02:21:38

标签: javascript jquery css animation css-grid

我想让一个元素滑到另一个网格单元上。我以为使用jQuery的.animate()方法会很容易,但是您不能在其中更改网格CSS。您也不能使用.css()方法,因为那样的话它会卡入到位,而不会滑入到位。

有没有一种简便的方法可以使用CSS和javascript / jQuery?我可以使用另一个API来简化此操作吗?老实说,我不知道从哪里开始。

1 个答案:

答案 0 :(得分:1)

我能想到的唯一方法就是几乎要伪造它?获取框的当前x / y坐标,将其放到新位置,获取新的x / y坐标,捕捉回去,使用position: relative对其进行动画处理,然后在完成动画后,移除相对位置并将其更新回正确的坐标。

类似这样的东西:

const b = document.getElementById('b');
document.getElementById('demo').addEventListener('click', function() {
    const { top: top1, left: left1 } = b.getBoundingClientRect();
    b.style.transition = '2s';
    b.style['grid-row-start'] = 3;
    b.style['grid-row-end'] = 4;
    const { top: top2, left: left2 } = b.getBoundingClientRect();
    b.style['grid-row-start'] = 2;
    b.style['grid-row-end'] = 3;
    setTimeout(() => {
        b.style.transition = 'auto';
        b.style['grid-row-start'] = 3;
        b.style['grid-row-end'] = 4;
        b.style.top = 0;
        b.style.left = 0;
    }, 2000);
    
    b.style.left = (left2 - left1) + 'px';
    b.style.top = (top2 - top1) + 'px';
});
body {
  margin: 40px;
}

.wrapper {
  display: grid;
  grid-template-columns: 100px 100px 100px;
  grid-gap: 10px;
  background-color: #fff;
  color: #444;
}

.box {
  top: 0;
  left: 0;
  transition: 2s;
  position: relative;
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}

.a {
  grid-column-start: 2;
  grid-column-end: 3;
  grid-row-start: 1;
  grid-row-end: 2;
}
.b {
  grid-column-start: 2;
  grid-column-end: 3;
  grid-row-start: 2;
  grid-row-end: 3;
}
.c {
  grid-column-start: 3;
  grid-column-end: 4;
  grid-row-start: 2;
  grid-row-end: 3;
}
.d {
  grid-column-start: 1;
  grid-column-end: 2;
  grid-row-start: 1;
  grid-row-end: 2;
}
.e {
  grid-column-start: 1;
  grid-column-end: 2;
  grid-row-start: 2;
  grid-row-end: 3;
}
.f {
  grid-column-start: 3;
  grid-column-end: 4;
  grid-row-start: 1;
  grid-row-end: 2;
}
<button id="demo">Click Me</button>
<div class="wrapper">
  <div class="box a">A</div>
  <div id="b" class="box b">B</div>
  <div class="box c">C</div>
  <div class="box d">D</div>
  <div class="box e">E</div>
  <div class="box f">F</div>
</div>