为文本创建摆动效果

时间:2017-09-20 17:47:31

标签: javascript jquery html css jquery-effects

所以我想要发生的是,当查看Span时,文本是正常的但是当你向下滚动它开始移动直到看起来像这样:

效果之前:
Before the effect

当效果发生时:
While the effect occurs

标题由每个字母的跨度表示。在初始状态中,每个的顶部像素值为0.但是提到的想法是在滚动值旁边改变。

我想通过JS和jQuery跟踪滚动位置,然后根据需要更改像素值。但这就是我遇到的麻烦。另外一个问题也是顺利进行。

2 个答案:

答案 0 :(得分:2)

对于偶数和奇数索引处的字符分别使用数学函数sine and cosine,因为函数的图形像波一样上下移动。这将产生平滑的效果:

Sine and cosine graphs

cos(x) == 1 - sin(x),所以从某种意义上说,每个角色都是"对立的"下一个创建分散的外观:



function makeContainerWiggleOnScroll(container, speed = 0.01, distance = 4) {
  let wiggle = function() {
    // y-axis scroll value
    var y = window.pageYOffset || document.body.scrollTop;
    // make div pseudo-(position:fixed), because setting the position to fixed makes the letters overlap
    container.style.marginTop = y + 'px';
    for (var i = 0; i < container.children.length; i++) {
      var span = container.children[i];
      // margin-top = { amplitude of the sine/cosine function (to make it always positive) } + { the sine/cosine function (to make it move up and down }
      // cos(x) = 1 - sin(x)
      var trigFunc = i % 2 ? Math.cos : Math.sin;
      span.style.marginTop = distance + distance * trigFunc(speed * y)/2 + 'px';
    }

  };
  window.addEventListener('scroll', wiggle);
  wiggle(); // init
}

makeContainerWiggleOnScroll(document.querySelector('h2'));
&#13;
body {
  height: 500px;
  margin-top: 0;
}
span {
  display: inline-block;
  vertical-align: top;
}
&#13;
<h2>
  <span>H</span><span>e</span><span>a</span><span>d</span><span>e</span><span>r</span>
</h2>
&#13;
&#13;
&#13;

重要造型说明: 跨度&#39; display必须设置为inline-block,以便margin-top正常工作

答案 1 :(得分:1)

这样的东西将是你JS功能的核心:

window.addEventListener('scroll', function(e) {
  var scrl = window.scrollY

  // Changing the position of elements that we want to go up
  document.querySelectorAll('.up').forEach(function(el){
    el.style.top = - scrl/30 +'px';
  });

  // Changing the position of elements that we want to go down
  document.querySelectorAll('.down').forEach(function(el){
    el.style.top = scrl/30 +'px';
  });
});

我们基本上是在收听滚动事件,检查用户滚动了多少,然后通过抵消我们的跨度来对其进行操作(我将其归类为&amp; amp;下)

JSBin Example

  

你可以改进自己的东西就是确保当用户滚动很多时这些字母不会离开页面。
  您可以通过简单的数学计算,考虑窗口的总高度并使用当前scrollY作为乘数来实现此目的。

- 正如RokoC指出的那样,还有改进性能的空间。
实施一些去抖动或其他类型的限制器