我正在尝试根据某人是向下滚动页面还是向上滚动页面来增加变量。每次向上或向下滚动时都会触发该事件,但该值仅增加一次。你们知道这是为什么吗?window.addEventListener("wheel", function (e) { const y = e.deltaY; let scrollIndex = 0; if (y > 0) { scrollIndex++; } else { scrollIndex--; } console.log(`Scroll index: ${scrollIndex}`);});
1 回答
POPMUISE
TA贡献1765条经验 获得超5个赞
因为您每次都设置新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}`);
});
添加回答
举报
0/150
提交
取消
