【问题标题】:CSS to pan background image back and forth [closed]CSS来回平移背景图像[关闭]
【发布时间】:2015-11-21 05:52:28
【问题描述】:

我正在寻找一种纯 CSS 方法来为背景图像设置动画,类似于此处给出的示例:

https://www.html5andbeyond.com/css3-animated-backgrounds-infinite-scrolling-background/

但我希望图像(山景)缓慢来回平移,而不是无限循环,因此在页面加载时,查看者会看到图像的左侧,几秒钟后会看到右侧,并且然后再回来。

一个重要的警告是带有背景的 div 是全宽的,所以要为动画设置绝对值。

感谢您的任何建议。

编辑:这是上面链接的示例中的滚动代码

<style>
@-webkit-keyframes backgroundScroll {
from {background-position: 0 0;}
to {background-position: -99999999px 0;} }

@keyframes backgroundScroll {
from {background-position: 0 0;}
to {background-position: -99999999px 0;} }

#mtn-scroll {
width: 100%;
height: 35em;
background: url(mtns.jpg) no-repeat;
-webkit-animation: backgroundScroll 999999s linear infinite;
animation: backgroundScroll 999999s linear infinite; }
</style>

<div id="mtn-scroll"></div>

【问题讨论】:

  • 你能把那篇文章中必要的代码贴在这里吗?
  • 请展示您在执行您要求的操作时所做的任何尝试,如果您的尝试导致问题,我们可以提供帮助。
  • 那么,为background-position 设置动画,然后在从一侧到另一侧再返回的无限循环中……
  • 相关代码将帮助我们帮助您。
  • 已编辑以包含代码示例。

标签: html css background-image css-animations


【解决方案1】:

您只需要将关键帧动画更改为百分比即可。

@keyframes backgroundScroll {
    0%   {background-position: 0 0;}
    50%  {background-position: -400px 0;}
    100% {background-position: 0 0;}
}

然后将动画时间加倍。

background: url(bg-repeat.png) repeat-y;
    animation: backgroundScroll 40s linear infinite;
}

【讨论】:

  • 嗯。这几乎可以工作,除了图像的边缘进入视口。但是有足够宽的图像可以工作。
【解决方案2】:

以 Hunter Turner 的回答为基础,这就是我最终得到的结果。

<style>
@keyframes backgroundScroll {
0% { background-position: 50% 50%; }
33% { background-position: 1% 50%; }
40% { background-position: 1% 50%; }
66% { background-position: 99% 50%; }
75% { background-position: 99% 50%; }
100% { background-position: 50% 50%; }}
/* added pauses to each edge of the image */

#mtn-scroll {
width: 100%;
height: 35em;
background: url(mtns.jpg) no-repeat;
background-size: 150%;
background-position: 50% 50%;
animation: backgroundScroll 60s ease-in-out 1s infinite; }
</style>

<div id="mtn-scroll"></div>

【讨论】:

    猜你喜欢
    • 2016-01-11
    • 2022-11-14
    • 2014-09-30
    • 2013-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    相关资源
    最近更新 更多