温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Using a wheel event to call a function that chooses new variables in the array
arrays ecmascript-6 javascript

javascript - 使用wheel事件调用在数组中选择新变量的函数

发布于 2020-03-27 10:23:22

我已经将wheel event-listener添加到HTML元素中。我的数组中有4个变量。现在,我的目标是,每当用户在添加事件(侦听器)的对象上滚动鼠标滚轮/触摸板时,都应选择下一个变量。

例如,我的数组就像[苹果,橙子,木瓜,番石榴]。我想创建一些东西,它将在移动时选择苹果,然后在下一个移动中选择橙色,然后在下一个移动中选择木瓜,依此类推。

而且方向相反(从番石榴到木瓜,每次用户滚动鼠标滚轮或向上滚动触摸板时都要进行安排)

我面临的问题是以下两个:

  1. 鼠标滚轮触发太多次,并多次调用函数(damnIt)。即使我编写了一个函数来按照我提到的顺序迭代数组。多次调用该函数将使事物随机化。

  2. 我什至不知道如何编写一个函数来在数组中引起这种迭代。到目前为止,这不是我的主要问题。

    var controller = document.querySelector(".main");
    var apple = document.querySelector(".box");
    var orange = document.querySelector(".box1");
    var papaya = document.querySelector(".box2");
    var guava = document.querySelector(".box3");
    var boxes = [apple,orange,papaya,guava];
    
    controller.addEventListener('wheel', damnIt);
    
    function damnIt(){
        console.log ("hey");
        //my function for array selection goes here
    }
    

查看更多

查看更多

提问者
Bon Leofen
被浏览
230
Vladislav Sevostyanov 2019-07-03 22:38

小跑方式(每150毫秒拨打一次)

var controller = document.querySelector(".main");
var apple = document.querySelector(".box");
var orange = document.querySelector(".box1");
var papaya = document.querySelector(".box2");
var guava = document.querySelector(".box3");
var boxes = [apple,orange,papaya,guava];

controller.addEventListener('wheel', throttle(damnIt, 150));

function damnIt() {
  console.log ("hey");

    //my function for array selection goes here
}

function throttle(cb, timeout) {
  // You can rewrite this function by replacing the time limit with the
  // scroll pitch. I think that would be the best solution.
  // let delta = e.deltaY || e.detail || e.wheelDelta;
  // ... sum delta and call callback by the number of steps: accumulator/step

  let lastCall = 0;

  return function() {
    if (new Date() - lastCall > timeout) {
      lastCall = new Date();

      cb();
    }
  }
}