如何用javascript调用函数,然后在滚动事件中调用该函数的特定实例

How would I call a function in javascript, and then later, on a scroll event, call that specific instance of the function?

本文关键字:调用 函数 实例 事件 javascript 何用 然后 滚动      更新时间:2023-09-26

我想运行一个函数(scrollSprite),该函数在加载时运行for循环,用一堆if语句"填充"它自己。然后在稍后的滚动事件中,我想称之为现在特定的"填充"或"构建"函数。我知道如何在滚动中调用函数,我的问题是我不知道如何调用函数的特定实例。

参见以下代码:

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);
        }
    }
}

任何方向都将不胜感激!感谢

您可以使用立即调用函数表达式(IIFE)。参见此示例:

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);