【问题标题】:CSS Keyframe to animate element to top of pageCSS关键帧动画元素到页面顶部
【发布时间】:2019-07-01 11:44:35
【问题描述】:

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

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')

我应该在顶部放置什么值才能占据 ion-row 的当前位置?或者我必须以其他方式做到这一点?

【问题讨论】:

    标签: css css-animations keyframe


    【解决方案1】:

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

    我使用存储在CSS 变量--move-y 中的偏移值将框的偏移量分配给custom property 和translate 框。

    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/

    【讨论】:

    • 最好在元素上设置自定义属性而不是根,以便它可以与任何元素一起使用......您也可以摆脱CSS中的定义并使用默认值var(--c,0)
    • @TemaniAfif 谢谢(更新)。没想到我可以放弃定义。
    【解决方案2】:

    由于您使用的是 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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2021-12-08
      • 1970-01-01
      相关资源
      最近更新 更多