javascript - 无法根据“wheel”事件侦听器增加值
问题描述
我正在尝试根据某人是向下滚动页面还是向上滚动页面来增加变量。
每次向上或向下滚动时都会触发该事件,但该值仅增加一次。你们知道这是为什么吗?
window.addEventListener("wheel", function (e) {
const y = e.deltaY;
let scrollIndex = 0;
if (y > 0) {
scrollIndex++;
} else {
scrollIndex--;
}
console.log(`Scroll index: ${scrollIndex}`);
});
解决方案
因为您每次都设置新scrollIndex
变量并将其等于零。放在scrollIndex
函数之外,它将起作用。例子:
let scrollIndex = 0;
window.addEventListener("wheel", function (e) {
const y = e.deltaY;
if (y > 0) {
scrollIndex++;
} else {
scrollIndex--;
}
console.log(`Scroll index: ${scrollIndex}`);
});
推荐阅读
- spring-boot - Spring引导数据redis不从存储库返回值
- signalr - 如何将 SignalR 与多页 Web 应用程序一起使用?
- onedrive - OneDrive Graph API 在移动到其他文件夹之前检测文件是否被任何用户打开
- flutter - 在 SharedPreferences 上颤振保存对象
- shiny - 控制搜索框位置 RenderDataTable R
- xamarin.forms - Azure DevOps Xamarin.iOS 模拟器生成输出
- java - 如何编写 mybatis 映射器以便在中间创建的临时表中插入?
- python - 在输出时订购 json jable
- python - 在 Python 中从子构造函数调用父构造函数的细微差别
- python - 根据有效的其他列计算数据框列的平均值两次