CSS3动画 - 当div的宽度发生变化时,图像会继续移动

时间:2017-10-13 14:54:41

标签: css3 animation

我试图模仿以下网站:http://shiz.co/http://www.maison-vignaux.com/work

图像显示的方式,它们不会移动,但更多的图像会在一个区间内显示出来。我想要这种类型的动画。现在,我的图像移动而不是像上面的网站那样显示更多。

我不知道如何做到这一点。

这是我的小提琴:https://jsfiddle.net/z7ukk6kb/(忽略动画的名称)

编辑:问题是div上的背景位置。现在它做我想做的事。

 <div class="parallax-elem">
   <div class="img"></div>
 </div>

$('.img').addClass('slide-top');

我的CSS:

.slide-top {
  -webkit-animation: slide-top 0.5s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
          animation: slide-top 0.5s cubic-bezier(0.250, 0.460, 0.450, 0.940) both;
}

@keyframes slide-top {
  0% {
      width:0;
  }
  100% {
      width:100%;
  }
}

.parallax-elem {
  overflow:hidden;
  position: absolute;
  height:600px;
  width:100%;
}

.parallax-elem:after {
  content:"";
  background-color:#eee;
  width:100%;
  height:100%;
  top:0;
  left:0;
  right:0;
  position: absolute;
  z-index:10;
}

.img {
  background:url('http://media.nj.com/entertainment_impact_dining/photo/coffee-stock-photo-0e8b300f42157b6f.jpg') no-repeat;
  background-size: cover;
  background-position: center center;
  position: relative;
  height: 100%;
  z-index:11;
    width: 100%;
}

2 个答案:

答案 0 :(得分:1)

尝试从background-position删除.img

由于您已设置background-position: center center,因此在动画期间div的宽度会增加,背景图像会一直调整以保持居中。这就是它继续前进的原因。

$('.img').addClass('slide-top');
.slide-top {
          animation: slide-top 0.5s cubic-bezier(0.250, 0.460, 0.450, 0.940) both infinite;
}


@keyframes slide-top {
  0% {
            width:0;
  }
  100% {
            width:100%;
  }
}

body {
  max-width:800px;
	margin:0 auto;
	position:relative;
}

.parallax-elem {
  overflow:hidden;
  position: absolute;
  height:600px;
  width:100%;
}

.parallax-elem:after {
  content:"";
  background-color:#eee;
  width:100%;
  height:100%;
  top:0;
  left:0;
  right:0;
  position: absolute;
  z-index:10;
}

.img {
  background:url('http://media.nj.com/entertainment_impact_dining/photo/coffee-stock-photo-0e8b300f42157b6f.jpg') no-repeat;
  background-size: cover;
  position: relative;
  height: 100%;
  z-index:11;
    width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parallax-elem">
    <div class="img"></div>
</div>

答案 1 :(得分:1)

发生这种情况的原因是因为您使用了背景位置中心。而这正是正在做的事情,它将你的形象与中心对齐。如果您更改为background-position: left center,问题就会解决,因为您可以看到in this fiddle

你也可以完全删除 background-position ,但是你也会失去垂直对齐,你可能不想要它。

此外,您可以更轻松地制作动画,不需要关键帧:

.img{
    width: 0%;
    background-position: left center;
    animation: width 0.5s cubic-bezier(0.250, 0.460, 0.450, 0.940);
}
.img.slide-top{
    width: 100%;
}
相关问题