首页 > 解决方案 > CSS动画随着旋转来回移动

问题描述

我正在尝试仅使用 CSS 制作一个非常简单的动画移动。我想做的是

对象在 200px 和 800px 之间来回移动,当对象到达边缘时,它会旋转它的方向。

.cow {
    width: 300px;
    position: absolute;
    top: 50px;
    left: 0px;
    animation: cowmove 5s linear both infinite alternate,
                rotate 0.3s linear 5s; 

}

@keyframes cowmove{
    from{transform: translateX(200px);}
    to{transform: translateX(800px);}
}

@keyframes rotate{
    from{transform: rotateY(0);}
    to{transform: rotateY(180deg);}
}

这是我迄今为止编写的代码,但旋转对我来说很难。

使用当前代码,对象将从 200px 移动到 800px,传送到 200px 点并旋转,传送回 800px 点并移回 200px。

这可能是非常简单的解决方案,但我很难弄清楚这一点:(

谢谢,

标签: css

解决方案


由于您处理相同的属性,因此只制作一个动画:

.cow {
  width: 80px;
  height: 80px;
  background: linear-gradient(blue 50%, red 0);
  border-radius: 50%;
  position: absolute;
  top: 50px;
  left: 0px;
  animation: cowmove 5s linear infinite;
}

@keyframes cowmove {
  0% {
    transform: translateX(100px) rotate(0);
  }
  30% {
    transform: translateX(400px) rotate(0);
  }
  50% {
    transform: translateX(400px) rotate(180deg);
  }
  80% {
    transform: translateX(100px) rotate(180deg);
  }
  100% {
    transform: translateX(100px) rotate(360deg);
  }
}
<div class="cow"></div>


推荐阅读