简体   繁体   English

如何在 vanilla javascript 中正确使用滚动事件监听器?

[英]How to correctly use the scroll eventListener in vanilla javascript?

How can I improve the code below?如何改进下面的代码?

I wish to use only one function to execute my code with the scroll event.我希望只使用一个函数来执行带有滚动事件的代码。 I have something like this:我有这样的事情:

function scrollMenu() {
 window.addEventListener("scroll", () => {
   // do stuff
 });
}
function scrollhabilities() {
 let cont = 0;
 window.addEventListener("scroll", () => {
   // do stuff
   };
 });
}

This works, but I tried to improve the code to be less repetative, however it doesn't work:这有效,但我试图改进代码以减少重复,但它不起作用:

const scrollmenu = () =>{}
const scrollhabilities = () =>{}

function scrollThings() {
  window.addEventListener("scroll", () => {
    scrollmenu();
    scrollhabilities():   
  });
}

Maybe this helps you to get a starting point.也许这可以帮助您找到一个起点。 (you can obviously remove the event parameter if you never need it inside the function) (如果您在函数内部永远不需要它,您显然可以删除事件参数)

 var scrollmenu = function(scrollEvent) { console.log('scrollmenu', window.scrollY) }; var scrollhabilities = function(scrollEvent){ console.log('scrollhabilities', window.scrollY) }; var scrollThings = function () { window.addEventListener("scroll", event => { scrollmenu(event); scrollhabilities(event); }); }();
 div.scroll { background-color: orange; height: 1000px; width: 400px; }
 <div class="scroll">move your cursor here and scroll up and down</div>

You might need a debounce function.您可能需要去抖动功能。 Debouncing allows your function to fire only once in the specified period of time (500ms in the below example).去抖动允许您的函数在指定的时间段内仅触发一次(以下示例中为 500 毫秒)。

Without this function, scrolling the window will fire thousands of times during a continuous scroll.如果没有此功能,在连续滚动期间滚动窗口将触发数千次。 With this function, it will fire only once.使用此功能,它只会触发一次。 As soon as the user pauses for the specified period of time (eg. 500ms), the function will fire.只要用户暂停指定的时间段(例如 500 毫秒),该功能就会触发。 (I set the timeout to 500ms to ensure the effect is seen - usually you would not specify such a large number - perhaps 100ms or less might be better.) (我将超时设置为 500 毫秒以确保看到效果——通常你不会指定这么大的数字——也许 100 毫秒或更短可能更好。)

Note that there is a companion function called "throttle" that is slightly different.请注意,有一个名为“throttle”的伴随函数略有不同。

 var cnt = 0; const msg = document.getElementById('msg'); window.addEventListener("scroll", () => { handleScroll(); }); const handleScroll = debounce(() => { cnt++; msg.innerText = cnt; },500); function debounce(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; };
 body{height:3000px;} #msg{ position:fixed; top:20px; right:2px; padding:2vh 5vw; font-size:5rem; background:wheat; border:1px solid orange; }
 <div id="msg"></div>

References:参考:

https://davidwalsh.name/javascript-debounce-function https://davidwalsh.name/javascript-debounce-function

this comment explains throttle 这条评论解释了油门

https://css-tricks.com/debouncing-throttling-explained-examples/ https://css-tricks.com/debouncing-throttling-explained-examples/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM