简体   繁体   English

调用函数onload,也onscroll吗?

[英]Call a function onload, and onscroll also?

I have a function which is called when the user scrolls. 我有一个在用户滚动时调用的函数。 Works well, but for elements those are on the top of the document (and on the top of the viewport of course), the effects inside the function executes after the first scroll. 效果很好,但是对于那些位于文档顶部(当然也是视口顶部)的元素,函数内部的效果在第一次滚动后执行。 I need to know if there's a way to do something like this: 我需要知道是否可以做这样的事情:

if(window.onscroll || window.onload){
    function toExecute(){}
}

The easiest way to do this would be to bind the same function to both the load and the scroll event. 最简单的方法是将相同的功能绑定到loadscroll事件。
However, since the scroll handler is called very rapidly and can easily cause performance issues on either mobile devices or older browsers, it's better to debounce the scroll handler. 但是,由于滚动处理程序被非常快速地调用,并且很容易在移动设备或较旧的浏览器上引起性能问题,因此最好对滚动处理程序进行去抖动处理。

 function foo() { console.log('foo called at ' + new Date()); } let timer; function debouncedFoo() { if (timer) return; timer = setTimeout(() => { timer = null; foo(); }, 20); } window.addEventListener('load', foo); window.addEventListener('scroll', debouncedFoo); 
 body { height: 3000px; } 

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

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