为什么我的动画不起作用?

时间:2017-04-04 08:05:50

标签: css3

我想让动作起作用,但背景图像的位置是固定的,不会移动,为什么?

@-webkit-keyframes anima {
    from {
        background-position: left;
    } to {
      background-position: right;
    }
}


#bando {
    border-radius: 4px;
    background-image: url(neon.jpg);
    background-size: 120%;
    width: 600px;
    padding-top:40px;
    padding-bottom:40px;
    margin-bottom: 10px;
    font-size: 30px;
    height:200px;
    animation-name: anima;
    animation-duration: 3s;
    animation-iteration-count: infinite;
    animation-timing-function: linear;
    animation-direction: alternate;
}

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

为此,请确保图像比元素更大(或更小),如下面的示例所示,元素宽度为600px,图像为800px

@-webkit-keyframes anima {
  from {
    background-position: left;
  }
  to {
    background-position: right;
  }
}

div {
  border-radius: 4px;
  background-size: 120%;
  background: url(http://lorempixel.com/800/280/nature/1/);
  width: 600px;
  padding-top: 40px;
  padding-bottom: 40px;
  margin-bottom: 10px;
  font-size: 30px;
  height: 200px;
  animation-name: anima;
  animation-duration: 3s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  animation-direction: alternate;
}
<div></div>

另一种选择是使用伪元素,因为您可以使用transform来移动图像,我建议使用这种格式,这是一种更加顺畅和有效的方法

div {
  position: relative;
  border-radius: 4px;
  width: 600px;
  padding-top: 40px;
  padding-bottom: 40px;
  margin-bottom: 10px;
  font-size: 30px;
  height: 200px;
  overflow: hidden;
}
div::after {
  content: '';
  position: absolute;
  border-radius: 4px;
  background-size: 120%;
  background: url(http://lorempixel.com/800/280/nature/1/);
  width: 800px;
  height: 100%;
  animation-name: anima;
  animation-duration: 3s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  animation-direction: alternate;
}

@-webkit-keyframes anima {
  from {
    transform: translateX(0);
  }
  to {
    transform: translateX(-200px);
  }
}
<div></div>