我正在尝试使用CSS转换来改善100%宽度包装器内元素的位置,以提高动画效果。因此,在重复动画之前,它从左侧进入屏幕,在右侧退出。

我想我可以为这个动画使用百分比。我发现的是,平移与您要设置动画的对象有关。

因此,如果您有一个100px宽的对象,并且将动画设置如下:

@keyframes moveme {
  0% { transform: translate(-100px, 150px) }
  100% { transform: translate(100%, 100px) }
}

对象将移动对象宽度的200%,即200px。

是否可以使用关键帧动画中的css变换来使对象移动到容器的宽度?

到目前为止,这是我的codepen codepen.io/matttunney/pen/dPMQZL

谢谢

最佳答案

您可以在元素周围使用包装器,将包装器的宽度设置为100%。并对其进行动画处理。

这样,您就可以将平移应用于元素宽度,但是元素宽度与容器宽度匹配

.banner {
  display:block;
  width:100%;
  height:300px;
  background:#0069aa;
  position:relative;
}
.moveme, .movewidth {
  position:absolute;
}
.movewidth {
  width:100px;
  height:100%;
  background: #edaf02;
  transform: translate3D(0,0,10px)
}
.wrapper {
  width: 100%;
  animation: moveme 10s linear infinite;
}
.moveme {
  background:#003356;
  width:100px;
  height:100px;
  transform: translate3D(0,150px,20px)
}
@keyframes moveme {
  0% { transform: translate(0%, 150px) }
  100% { transform: translate(100%, 100px) }
}

demo

正如Simon_Weaver指出的那样,具有2个宽度为100%的元素令人困惑。目前尚不清楚哪个是建议的解决方案。

更好的演示

.banner {
  display:block;
  width:400px;
  height:300px;
  background:#0069aa;
  position:relative;
}
.moveme, .movewidth {
  position:absolute;
}
.movewidth {
  width:100px;
  height:100%;
  background: #edaf02;
  transform: translate3D(0,0,10px)
}
.wrapper {
  width: 100%;
  -webkit-animation: moveme 1s linear infinite;
  animation: moveme 1s linear infinite;
}
.moveme {
  background:#003356;
  width:100px;
  height:100px;
  transform: translate3D(0,150px,20px)
}
@keyframes moveme {
  0% { transform: translate(0%, 150px) }
  100% { transform: translate(100%, 100px) }
}
@-webkit-keyframes moveme {
  0% { transform: translate(0%, 150px) }
  100% { transform: translate(100%, 100px) }
}
  <div class="banner">
      <div class="movewidth">
      </div>
      <div class="wrapper">
      <div class="moveme">
      </div>
      </div>
    </div>

关于css - 使用css变换使对象在其父对象的整个宽度上进行动画处理,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27482058/

10-12 12:28
查看更多