代码之家  ›  专栏  ›  技术社区  ›  niklas

Css顺序动画搞砸了

  •  0
  • niklas  · 技术社区  · 8 年前

    我想实现一个连续的css动画,其中一个div围绕另一个div的边界移动。两个方向工作(从下到上和从右到左)的作品,其他似乎混淆了。

    我的密码是

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      -ms-box-sizing: border-box;
    }
    body {
      background: #000;
    }
    .box-outer {
      overflow: hidden;
      margin: 50px auto;
      width: 200px;
      height: 200px;
    }
    .main_box {
      width: 200px;
      height: 200px;
      position: relative;
      background: #f34c4c;
      border: 10px solid #000;
    }
    .bar {
      position: absolute;
      width: 10px;
      height: 10px;
      background: #fff;
      top: -10px;
      left: -10px;
      animation-name: move-right, move-down, move-left, move-up;
      animation-delay: 0, 2s, 4s, 6s;
      animation-duration: 2s, 2s, 2s, 2s;
      animation-iteration-count: infinite, infinite, infinite, infinite;
    }
    
    @keyframes move-right {
      0% {
        left: -10px;
      }
      25% {
        left: 100%;
      }
    }
    @keyframes move-down {
      26% {
        top: -10px;
      }
      50% {
        top: 100%;
      }
    }
    @keyframes move-left {
      51% {
        left: 100%;
      }
      75% {
        left: -10px;
      }
    }
    @keyframes move-up {
      76% {
        top: 100%;
      }
      99% {
        top: -10px;
      }
    }
    <div class="box-outer">
      <div class="main_box">
        <div class="bar"></div>
      </div>
    </div>
    1 回复  |  直到 8 年前
        1
  •  2
  •   Quentin    8 年前

    这是因为你必须设置两者 top left 每个关键帧中的值。
    顺便说一下,你可以用一个动画,而不是4个。

    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      -ms-box-sizing: border-box;
    }
    
    body {
      background: #000;
    }
    
    .box-outer {
      overflow: hidden;
      margin: 50px auto;
      width: 220px;
      height: 220px;
    }
    
    .main_box {
      width: 220px;
      height: 220px;
      position: relative;
      background: #f34c4c;
      border: 10px solid #000;
    }
    
    .bar {
      position: absolute;
      width: 10px;
      height: 10px;
      background: #fff;
    }
    
    .top {
      top: -10px;
      left: -10px;
      animation: move 4s infinite linear;
    }
    
    @keyframes move {
      0% {
        top: -10px;
        left: -10px;
      }
      25% {
        top: -10px;
        left: 200px;
      }
      50% {
        top: 200px;
        left: 200px;
      }
      75% {
        top: 200px;
        left: -10px;
      }
    }
    <div class="box-outer">
      <div class="main_box">
        <div class="bar top"></div>
      </div>
    </div>