CSS关键帧无限水平滚动?

9
作为一名学生,我正在制作自己的作品集。
对于页眉,我尝试创建一个天空效果,使用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>

3
通常的做法是使图像以与开始相同的方式结束,这样动画自然地感觉像循环。它应该完全匹配整个视口,以使其成为无缝过渡。 - Juan Ferreras
正如@JuanFerreras所提到的,这就是所有动画的工作原理,它从一开始就开始,并使结尾与开头相同,以Gif为例。 - Mohammad Al Baghdadi
1个回答

20

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

Explanation Image

裁剪后的图片:

裁剪的云

How it works

@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>

Final result

@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;)”是在一个图像的宽度处,从右到左运行。我需要从左到右,所以我将其解决为“to {background-position: 2000px 0;}”。只是提出来,也许有人会遇到类似我的情况。 - Mugé

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接