首页 > 解决方案 > 改变方向时横向滚动抖动

问题描述

我使用 jQuery 和鼠标滚轮插件制作了自己的横向滚动视差。到目前为止,它工作得很好,除了当我改变滚动方向时,它在实际滚动之前首先抖动(好像它在实际移动到正确的一个单元之前将一个单元滚动到前一侧)。我已经尝试为此添加一个处理程序,它可以完全停止滚动。

到目前为止,这是我的脚本:

var scroll = 0; // Where the page is supposed to be
var curr = scroll; // The current location while scrolling
var isScrolling = false; // Tracker to check if scrolling
var previous = 0; // Tracks which direction it was previously
var loop // setInterval variable

function parallax() {
  isScrolling = true;

  // Loops until it's where it's supposed to be
  loop = setInterval(() => {
    if ( curr - scroll == 0 ) {
      clearInterval(loop);
      isScrolling = false;
      return;
    }

    // Move the individual layers
    $('.layer').each(function() {
      $(this).css('left', -curr * $(this).data("speed"));
    });

    // Add/subtract to current to get closer to where it's supposed to be
    curr += (scroll < curr) ? -0.5 : 0.5;

  }, 25);
}

$(document).ready(() => {
  $('.scrolling-container').mousewheel((e, dir) => {
    e.preventDefault();

    // If the speed's magnitude is greater than 1, revert it back to 1
    if ( Math.abs(dir) > 1) {
      dir = Math.sign(dir);
    }

    // If the direction changes, stop the current animation then set scroll to where it currently is
    if ( previous !== dir ) {
      previous = dir;
      isScrolling = false;
      scroll = curr;
      clearInterval(loop);
    }

    // If not at the left most scrolling to the left, add to scroll
    if ( scroll - dir >= 0 ) scroll -= dir;

    // Call parallax function if it's not yet running
    if ( !isScrolling ) {
      parallax();
    }
  })
})

我认为它更容易展示,所以这里是功能部分的代码笔:https ://codepen.io/ulyzses/pen/yLyoYZm

尝试滚动一段时间然后改变方向,抖动行为应该很明显。

标签: javascriptjqueryhtmlscrollparallax

解决方案


推荐阅读