【问题标题】:CSS infinite horizontal scroll with keyframe?CSS无限水平滚动与关键帧?
【发布时间】:2021-05-21 08:21:45
【问题描述】:

作为一名学生,我实际上是在制作自己的作品集。
对于标题,我尝试创建天空效果,图像水平滚动。我使用了 CSS 和关键帧,我遇到的问题是当图像结束时,它会“重置”并且不能继续平滑滚动。
有没有办法让它“无限期地”继续下去? (我将持续时间更改为 5 秒,只是为了不让您等待 40 秒:p)

@keyframes animatedBackground {
  from { background-position: 0 0; }
  to { background-position: 100% 0; }
}
#header-top {
  height: 190px;
  background-image: url('http://image.noelshack.com/fichiers/2016/46/1479595480-clouds.png');
  background-repeat: repeat-x;
  animation: animatedBackground 5s linear infinite;
  line-height: 400px;

}
<div id="header-top">
</div>

【问题讨论】:

  • 这种事情的通常做法是让图像以与开始时相同的方式结束,这样动画自然会感觉像是在循环。它应该与整个视口完全匹配,以使其成为无缝过渡。
  • @JuanFerreras 提到这就是所有动画的工作方式,它从头开始,它们使结尾与开头 Gif 的开头相同

标签: css css-animations keyframe


【解决方案1】:

我刚刚裁剪了您的图像,因此结尾与开头对齐。然后,我修改了 animatedBackground 关键帧以在图像的另一端结束。

裁剪图像:

工作原理

@keyframes animatedBackground {
  from {
    left: 0px;
  }
  90% {
    left: -562px;
  }
  100%{left: 0px;}
}
#header-top {
  height: 190px;
  width: 562px;
  overflow-x: auto;
  overflow-y: hidden;
}
* {
  margin: 0;
  padding: 0;
  font-family:sans-serif;
}
.inner-cont {
  width: 1126px;
  position: relative;
  animation: animatedBackground 4s linear infinite;
}
img{
  border-right:1px solid black;
  box-sizing:border-box;
}
<div id="header-top">
  <div class='inner-cont'>
    <img src="https://archive.org/download/clouds-tiled/clouds-tiled.png" /><img src="https://archive.org/download/clouds-tiled/clouds-tiled.png" />
  </div>
</div>
<h3>^ How it actually works(almost) ^</h3>
<h4>The spinback doesn't actually get animated, but it happens <br/>(The line separates the looped images from each other)</h4>

最终结果

@keyframes animatedBackground {
  from { background-position: 0px 0; }
  to { background-position: -562px 0; }
}
#header-top {
  height: 190px;
  width:100%;
  background-image: url('https://archive.org/download/clouds-tiled/clouds-tiled.png');
  background-repeat: repeat-x;
  animation: animatedBackground 2s linear infinite;
  line-height: 400px;

}
<div id="header-top">
    </div>

【讨论】:

  • 太好了,谢谢!添加到您的解决方案中,因为我花了一些时间来确定一些 CSS 以及图像被剪切的位置。可以说,并排有 5 张图像。第一个图像被切成两半。最后一张图片被切成两半。您的图像宽 562 像素。我的图像是 2000 像素宽。在@keyframes 内,您的'to {background-position: -562px 0;) 位于您的一张图像的宽度处,从右到左运行。我需要从左到右,所以我把它解决为'到{背景位置:2000px 0;}。只是把它放在那里,也许有人会偶然发现与我相似的场景。
猜你喜欢
  • 2012-09-29
  • 2012-03-15
  • 1970-01-01
  • 1970-01-01
  • 2013-01-01
  • 1970-01-01
  • 2011-06-25
  • 2012-04-13
  • 1970-01-01
相关资源
最近更新 更多