图像无限滚动

时间:2018-09-08 12:20:26

标签: javascript jquery css css-animations

我正在尝试实现以下效果:每个图像在滚动时向上移动,每个图像以不同的速度移动,并从屏幕顶部移出,并以无限循环从页面底部重新出现。 下图

任何示例或建议将不胜感激,谢谢

enter image description here

编辑:https://codepen.io/JTParrett/pen/BkDie

这是一个完美的示例,但是我希望滚动是无限的,并且对象应从底部重新出现

$.fn.moveIt = function(){
var $window = $(window);
var instances = [];

$(this).each(function(){
instances.push(new moveItItem($(this)));
});

window.addEventListener('scroll', function(){
var scrollTop = $window.scrollTop();
instances.forEach(function(inst){
  inst.update(scrollTop);
});
}, {passive: true});
}

var moveItItem = function(el){
this.el = $(el);
this.speed = parseInt(this.el.attr('data-scroll-speed'));
};

moveItItem.prototype.update = function(scrollTop){
this.el.css('transform', 'translateY(' + -(scrollTop / this.speed) + 
'px)');
};

// Initialization
$(function(){
$('[data-scroll-speed]').moveIt();
});

2 个答案:

答案 0 :(得分:1)

您可以使用纯CSS解决方案来产生所需的效果,可以使用CSS animations创建该效果。在下面的示例中,所有元素都位于网格中,并且同一动画gotop的每个项目执行时间都不同。

div {
  position: fixed;
  left: 0;
  width: 100%;
  height: 100%;
  display: grid;
  grid-column-gap: 5%;
  grid-template-columns: auto auto auto auto;
  overflow: hidden;
}

div.inner-container::-webkit-scrollbar {
  display: none;
}

.A {
  height: auto;
  animation-name: gotop;
  animation-duration: 3s;
  animation-iteration-count: infinite;
}

.B {
  height: auto;
  animation-name: gotop;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}

.C {
  height: auto;
  animation-name: gotop;
  animation-duration: 6s;
  animation-iteration-count: infinite;
}

.D {
  height: auto;
  animation-name: gotop;
  animation-duration: 9s;
  animation-iteration-count: infinite;
}

@keyframes gotop {
  from {
    margin-top: 120%;
  }
  to {
    margin-top: -20%;
  }
}
<div>
  <p class="A">
    textA
  </p>
  <p class="B">
    textB
  </p>
  <p class="C">
    textC
  </p>
  <p class="D">
    textD
  </p>
</div>

答案 1 :(得分:0)

对于初学者,您应该在图像中具有绝对的位置。

<img src="..." style="position: absolute; left: XXXpx: top: YYYpx;" data-scrollamount="ZZZ" />
<img src="..." style="position: absolute; left: XXXpx: top: YYYpx;" data-scrollamount="ZZZ" />
<img src="..." style="position: absolute; left: XXXpx: top: YYYpx;" data-scrollamount="ZZZ" />
<img src="..." style="position: absolute; left: XXXpx: top: YYYpx;" data-scrollamount="ZZZ" />
.
.
.
.

这样,您可以调整每个图像的开始位置。每个图像的滚动量也将不同。 然后,为窗口滚动事件添加事件侦听器。这是一些代码:

window.addEventListener("scroll", function(){
    images.each(function(){
        this.style.top += this.dataset.scrollamount
    }
}