首页 > 解决方案 > 无法根据“wheel”事件侦听器增加值

问题描述

我正在尝试根据某人是向下滚动页面还是向上滚动页面来增加变量。

每次向上或向下滚动时都会触发该事件,但该值仅增加一次。你们知道这是为什么吗?

window.addEventListener("wheel", function (e) {
  const y = e.deltaY;
  let scrollIndex = 0;
  if (y > 0) {
    scrollIndex++;
  } else {
    scrollIndex--;
  }
  console.log(`Scroll index: ${scrollIndex}`);
});

标签: javascript

解决方案


因为您每次都设置新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}`);
});

推荐阅读