[英]How would I call a function in javascript, and then later, on a scroll event, call that specific instance of the function?
I want to run a function (scrollSprite) that on load runs through a for loop, "populating" itself with a bunch of if statements. 我想运行一个函数(scrollSprite),该函数在加载时会通过for循环运行,并用一系列if语句“填充”自身。 Then later on a scroll event I want to call this now specific "populated" or "built" function. 然后,在以后的滚动事件中,我想将此功能称为现在特定的“填充”或“内置”功能。 I know how to call a function on scroll, my problem is specifically that I don't know how to call the specific instance of the function. 我知道如何滚动调用函数,我的问题特别是我不知道如何调用函数的特定实例。
See code below: 参见下面的代码:
var scrollSprite = function(distance, frames, frameSize, scrollInterval){
minScroll = 0;
maxScroll = -scrollInterval;
for (i = 0; i < frames; i++){
if(distance < minScroll && distance >= maxScroll){
$('#sprite').css("top", -scrollInterval);
}
minScroll = maxScroll;
maxScroll -= scrollInterval;
}
}
window.addEventListener("scroll", function(e){
if($('#finding-finders').hasClass('active')){
var scrollTop = $(window).scrollTop(),
elementOffset = $('#finding-finders').offset().top;
distance = (elementOffset - scrollTop);
//if the the element has reached the window then run instance of scrollSprite
if(distance < 0){
scrollSprite(distance, 10, 300, 20);
}
}
}
Any direction would be greatly appreciated! 任何方向将不胜感激! Thank you 谢谢
You can use an Immediately-Invoked Function Expression (IIFE). 您可以使用立即调用函数表达式(IIFE)。 See this example: 请参阅以下示例:
var scrollFn = (function() {
// code here to do something immediately
// return a new function
return function(event) {
// code here to run when scrolling
};
})(); // immediately invoke function
window.addEventListener('scroll', scrollFn);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.