javascript - 改变方向时横向滚动抖动
问题描述
我使用 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
尝试滚动一段时间然后改变方向,抖动行为应该很明显。
解决方案
推荐阅读
- java - Java Discord Bot (JDA) 检查是否固定
- python - python dataframe - 根据另一列中的子字符串条件创建新列
- javascript - 当我在 Filemanager plunig 中使用 Vue.js 或如何调用全局函数时,如何将文件上传到服务器?
- java - 在类路径资源中为具有额外列的多对多映射创建名称为“entityManagerFactory”的 bean 时出错
- javascript - ES6 动态导入问题
- python - Django中过滤数据的问题
- python - F2PY 模块未加载到笔记本中
- windows - 为什么调用ZwOpenKey时ACCESS_MASK的值为0也成功
- security - 零知识加密(用户控制的端到端加密)如何工作?
- python - 如何有效地遍历大型数据框,按列值,并重新连接在一起