更改背景位置而不动画

时间:2017-05-24 07:29:51

标签: html css html5 css3

我已经将此代码用于改变CSS和HTML中的背景:

animation: animated 10s linear infinite;

@keyframes animated {
    0% { background-position: 0px bottom; }
    25% { background-position: -200px bottom; }
    50% { background-position: -400px bottom; }
    75% { background-position: -600px bottom; }
}

目前背景在动画中移动,但我希望一次性使用背景切换位置 - 所以看起来图像会改变而不是移动。

只有CSS可以吗?

4 个答案:

答案 0 :(得分:1)

您需要做的是,而不是

25% { background-position: -200px bottom; }
50% { background-position: -400px bottom; }

你这样做:

25.01%, 50% { background-position: -200px bottom; }
50.01%, 75% { background-position: -400px bottom; }

因此,您将几乎消除从一个关键帧过渡到另一个关键帧所需的时间。

演示:jsFiddle



*{ padding:0; margin:0; }
#bg{ width:100%; height:100vh;
  background: url('//www.planwallpaper.com/static/images/Fall-Nature-Background-Pictures.jpg') no-repeat;
  animation: slideshow 5s infinite;
}
@keyframes slideshow {
  0%, 25% { background-position: 0px bottom; }
  25.01%, 50% { background-position: -200px bottom; }
  50.01%, 75% { background-position: -400px bottom; }
  75.01%, 100% { background-position: -600px bottom; }
}

<div id="bg"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用以下内容:

animation: animated 10s steps(4) linear infinite;
@keyframes animated {
  from {
    background-position: 0px 0px; }
  to {
    background-position: 600px 0px; }
}

答案 2 :(得分:0)

您可以删除CSS中的linear

animation: animated 10s infinite;

@keyframes animated {
    0% { background-position: 0px bottom; }
    25% { background-position: -200px bottom; }
    50% { background-position: -400px bottom; }
    75% { background-position: -600px bottom; }
}

答案 3 :(得分:0)

您需要使用setTimeout 10000ms的{​​{1}}来切换背景位置

$(document).ready(function () {
  var koef = 1;

  setInterval(function () {
    $('#image').css({'background-position-x': 600 * -koef});
    koef = !koef;
  }, 1000);
});
#image {
  width: 200px;
  height: 200px;
  background: url(http://lorempixel.com/g/1000/200/) no-repeat 0 bottom;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image"></div>