基于滚动百分比的动画翻译

jQuery Animate translateY Based On Scroll Percentage

本文关键字:百分比 动画 翻译 滚动 于滚动      更新时间:2023-09-26

我试图在没有任何插件的情况下建立一个简单的重叠"视差"效果。我有这样的html:

<section>
    <h2>Example Text</h2>
</section>
<section>
    <h2>Example Text</h2>
</section>
<section>
    <h2>Example Text</h2>
</section>
<section>
    <h2>Example Text</h2>
</section>
<section>
    <h2>Example Text</h2>
</section>

每个部分的高度为视窗的100%。我在$(window).scroll()中使用每个循环。我需要动画的transform: translateY()属性的顶部部分,直到以下部分是在浏览器的顶部。这个百分比基本上需要基于浏览器顶部的百分比。我尝试了一些事情,包括获得offset().topheight()值,并将它们与$(window).scrollTop()进行比较,但我似乎无法解决。这是我试图实现的效果,虽然它使用jQuery插件。

http://codepen.io/rocbear/pen/bdIaG

编辑我现在差不多解决了,但我有一个小问题回到顶部。translate属性不会一直回到0%,并在顶部留下一个空白。

我的合作者:http://codepen.io/mdmoore/pen/MwjoLZ

$(function(){
  $('section').each(function() {
    var off = $(this).offset().top
    $(this).data('orig-offset', off);
  });
  $(window).scroll(function(){
    var scrollTop = $(window).scrollTop();
    $('section').each(function(){
      var off = $(this).data('orig-offset');
      var translate =  (scrollTop - off) / $(window).height() * 100;
      if (scrollTop >= off) {
        $(this).css({transform: 'translateY(' + translate +'%)'});
      }
    });
  });
});

有一种方法。如果你愿意,可以随意优化它。

$(function(){
  $('section').each(function() {
    var off = $(this).offset().top
    $(this).data('orig-offset', off);
  });
  $(window).scroll(function(){
    var scrollTop = $(window).scrollTop();
     $('section').each(function(){
      var off = $(this).data('orig-offset');
      
       
      if (scrollTop >= off) {
        var translate =  (scrollTop - off) / $(window).height() * 100;
        console.log(translate);
        $(this).css({transform: 'translateY(' + translate +'%)'});
      }
     });
  });
});
html, body {
  height: 100%;
  margin: 0;
}
h2 {
  margin: 0;
  text-align: center;
}
section {
  background: #000;
  height: 100%;
  width: 100%;
  position: relative;
  top: 0;
}
section:first-of-type {
  background-color: coral;
}
section:nth-of-type(2) {
  background-color: lightgreen;
}
section:nth-of-type(3) {
  background-color: lightblue;
}
section:nth-of-type(4) {
  background-color: #ffff6e;
}
section:nth-of-type(5) {
  background-color: #3c3c3c;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="top">
<h2>Some Text</h2>
</section>
<section>
<h2>Some Text</h2>
</section>
<section>
<h2>Some Text</h2>
</section>
<section>
<h2>Some Text</h2>
</section>
<section>
<h2>Some Text</h2>
</section>