使用css转换在其父级宽度上为对象设置动画

Mat*_*att 6 css animation transform css3 translate-animation

我正在尝试使用css转换来改善我的动画性能,以便在100%宽度的包装器中转换元素的位置.因此,在重复动画之前,它从左侧进入屏幕并在右侧退出.

我想我可以使用这个动画的百分比.我发现的是,翻译是相对于你动画的对象.

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

@keyframes moveme {
  0% { transform: translate(-100px, 150px) }
  100% { transform: translate(100%, 100px) }
}
Run Code Online (Sandbox Code Playgroud)

该对象将移动200%的对象宽度,因此200px.

是否有修复方法使对象移动到容器的宽度,在关键帧动画中使用css变换?

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

谢谢

val*_*als 4

您可以在元素周围使用包装器,将包装器的宽度设置为 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) }
}
Run Code Online (Sandbox Code Playgroud)

演示

正如 Simon_Weaver 指出的那样,有 2 个宽度为 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) }
}
Run Code Online (Sandbox Code Playgroud)
.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) }
}
Run Code Online (Sandbox Code Playgroud)