使用javascript滚动滚动条或鼠标滚轮后的火灾事件

时间:2012-01-19 18:50:47

标签: javascript jquery

我想知道在使用滚动条或鼠标滚轮(或在触摸设备上轻扫)时,是否可以在滚动页面后触发事件。< / p>

基本上,我想检测用户何时停止滚动,以便我可以加载AJAX,而不是在滚动时加载。

似乎jQuery's .scroll()每次用户滚动时都会触发,并且一直有事件触发似乎很笨拙。是否.onScrollAfter().onMouseUp()同义?

我想知道这是否可行(或者如果函数已经存在)而不使用框架,尽管我会考虑一个;特别是jQuery

3 个答案:

答案 0 :(得分:7)

此事件不存在。您可以使用超时来模拟它:

示例(概念代码):

(function() {
    var timer;
    /* Basic "listener" */
    function scroll_finish(ev) {
        clearTimeout(timer);
        timer = setTimeout(scroll_finished, 200, ev);
        //200ms. Too small = triggered too fast. Too high = reliable, but slow
    }
    window.onscroll = scroll_finish; // Or addEventListener, it's just a demo

    // Fire "events"
    var thingey = [];
    function scroll_finished(ev) {
        // Function logic
        for (var i=0; i<thingey.length; i++) {
            thingey[i](ev);
        }
    }
    // Add listener
    window.addScrollListener = function(fn) {
        if (typeof fn  === 'function') {
            thingey.push(fn);
        } else {
           throw TypeError('addScrollListener: First argument must be a function.');
        }
    }
    window.removeScrollListener = function(fn) {
        var index = thingey.indexOf(fn);
        if (index !== -1) thingey.splice(index, 1);
    }
})();

答案 1 :(得分:3)

以为我会把它作为答案添加,即使它已经过时了。您尝试重新创建的事件我认为是debounce的同义词。这可以在underscore.js

中找到
  

debounce_.debounce(功能,等待,[立即])   创建并返回传递函数的新debounced版本,该函数将推迟执行,直到自上次调用之后经过等待毫秒。用于实现仅在输入停止到达后才会发生的行为。例如:渲染Markdown注释的预览,在窗口停止调整大小后重新计算布局,等等。

因此它将在您上次执行特定事件后等待。如果你不想要延迟,你可以指定0. David Walsh has a pretty nice implementation,你可以包含在任何项目中。

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

您可以通过

继续添加
var myEfficientFn = debounce(function() {
    // All the taxing stuff you do
}, 250);

window.addEventListener('scroll', myEfficientFn);

答案 2 :(得分:2)

描述

您可以使用jQuery插件特殊滚动事件为James Padoley提供的jQuery插件

工作真的很棒。

查看页面和jsFiddle Demonstration(只需滚动;))

更多信息