CSS 将元素动画到页面顶部的关键帧

CSS Keyframe to animate element to top of page

我想为页面顶部的元素设置动画。事情是这样的:

HTML:

...
<ion-row id="theHistory"></ion-row>
...

CSS:

@keyframes floatBubble {
    0% {
        top:??;
    }
    100% {
        top: 0px;
    }
}
.element-up{
    z-index:10;
    background-color:white;

    -webkit-animation: floatBubble 2s infinite  normal ease-out;
    animation: floatBubble 2s infinite  normal ease-out;
    position: absolute;
}

JS:

scrollToHistory.classList.add('element-up')

我应该在 top 中输入什么值来获取 ion-row 的当前位置?或者我必须以其他方式执行此操作?

由于您使用的是 JS,因此您可以动态设置 top 属性,无需向关键帧添加任何内容:

function move(e) {
  e.style.top = e.offsetTop + "px";
  e.classList.add('element-up');
}
@keyframes floatBubble {
  100% {
    top: 0px;
  }
}

div.element-up {
  z-index: 10;
  animation: floatBubble 2s forwards;
  position: absolute;
}

.box {
  width: 50px;
  height: 50px;
  background: red;
}

body {
 margin:0;
 padding:50px;
}
<div class="box" onclick="move(this)">
</div>

我喜欢@Temani 的解决方案,但我使用的是 transform,它创建的动画比 top 更流畅。使用 transform/translate 框将提升到它自己的渲染层。

我使用存储在 CSS 变量 --move-y.

中的偏移值将框的偏移量分配给 custom propertytranslate

const box = document.querySelector(".box");
box.addEventListener("click", move);

function move(e) {
  const distanceFromTop = (this.offsetTop * -1) + "px";
  this.style.setProperty("--move-y", distanceFromTop);
  this.classList.add("element-up");
}
@keyframes floatBubble {
  to {
    transform: translateY(var(--move-y, 0));
  }
}

div.element-up {
  z-index: 10;
  animation: floatBubble 2s forwards;
  position: absolute;
}

.box {
  width: 50px;
  height: 50px;
  background: red;
}

body {
  margin: 0;
  padding: 50px;
}
<div class="box">
</div>

https://jsfiddle.net/orvcn7y3/