根据滚动位置向变量计算添加缓动

问题描述

我有一些文本元素应该根据滚动位置在其x轴上移动。 请参阅此笔作为参考:

https://codepen.io/magglomag/pen/GRZwRNB

HTML

<h1 class="moving-text-wrapper">
  <div class="moving-text moving-text-1" data-scroll-speed="-4">Lorem</div>
  <div class="moving-text moving-text-2" data-scroll-speed="2">ipsum</div>
  <div class="moving-text moving-text-3" data-scroll-speed="9">sonsetetur</div>
  <div class="moving-text moving-text-4" data-scroll-speed="-6">sit</div>
  <div class="moving-text moving-text-5" data-scroll-speed="3">amet</div>
</h1>

CSS

html {
  height: 300vh;
}

.moving-text-wrapper {
  margin-top: 100vh;
  text-align: center;
}

jQuery

$.fn.moveIt = function(){
  var $window = $(window);
  var instances = [];
  
  $(this).each(function(){
    instances.push(new moveItItem($(this)));
  });
  
  window.addEventListener('scroll',function(){
    var scrollTop = $window.scrollTop();
    var elemOffsetTop = $( '.moving-text-wrapper' ).offset().top;
    var translateX = elemOffsetTop - scrollTop - $( window ).height()/2;

    instances.forEach(function(inst){
      inst.update(translateX);
    });
  },{passive: true});
}

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

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

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

我要添加的变量translateX稍微放松一点,所以当滚动停止时,文本将移动更长一点,并且不会像当前的笔一样直接停止。

有人提示如何解决吗? 非常感谢!

解决方法

实际上,使用CSS过渡很容易解决这个问题:

我刚刚向这样的元素添加了过渡:

.moving-text {
  transition-property: transform;
  transition-duration: 1s;
  transition-timing-function: ease-out;
}

请参阅更新的Codepen以获取参考: https://codepen.io/magglomag/pen/YzqRPoX

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...