滚动结束后如何调用函数? [英] How to call a function after scroll has ended?

查看:77
本文介绍了滚动结束后如何调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在滚动结束后立即调用一个函数.我尝试了 load 各种不同的方法,但都没有奏效,然后在SO中找到了这种解决方案:

I want to call a function right after a scroll ends. I have tried a load of different things, none of which have quite worked, and then I came upon this solution in SO:

如何知道何时停止滚动Javascript

我仔细看了一下第二个答案并尝试了-它可以工作.然后,我尝试为自己的目的对其稍作更改.所以现在整个shebang看起来像这样:

I took a good look at the second answer and tried it - it works. Then I tried to change it slightly for my purposes. So now the whole shebang looks like this:

<!DOCTYPE html>
<html>

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Do something after scroll ends</title>

<style type="text/css">
    #scrollableDiv{
        width:500px;
        height:100px;
        overflow:scroll;
    }

    #someContent{
        width:600px;
        height:200px;
    }
</style>

<script type="text/javascript" src="scripts/jquery-1.5.1-min.js"></script>

<script type="text/javascript">
    $(document).ready(function() {

        $('#scrollableDiv').bind('scroll', bodyScroll);

        var scrollTimer = -1;

        function bodyScroll() {
            console.log('scrolling.');

            if (scrollTimer != -1)
                clearTimeout(scrollTimer);

            scrollTimer = window.setTimeout('scrollEnded()', 500);

        };

        function scrollEnded(){
            console.log('scrollEnded. Now do something astounding.');
        };

    });
</script>

</head>

<body>

<div id="scrollableDiv">
    <div id="someContent">
        Scroll me.  
    </div>
</div>

</body>
</html>

运行此命令时,滚动事件会触发(很棒!).

When I run this, the scroll event triggers (great!).

然后,而不是调用我的"scrollEnded()"函数,而是生成了一个错误:"scrollEnded未定义".我试图通过进入调试模式并逐步执行脚本来找出问题的根源,但是随后我进入了一个匿名函数",这就是我目前对这个问题的理解的极限.我试过将scrollEnded()函数移到顶部.我已经尝试过各种方法...

Then, instead of calling my "scrollEnded()" function, an error is generated: "scrollEnded is not defined". I've tried to figure out where this comes from by going into debug mode and stepping through the script, but then I land up in an "anonymous function" - which is where I hit the limits of my current understanding of this problem. I've tried moving the scrollEnded() function to the top. I've tried all sorts of things...

我该怎么做才能使它起作用? (可以行吗?)

What can I do to make this work? (Can this thing work?)

推荐答案

jQuery throttle /debounce插件非常适合此操作.使用at_begin = false最后执行回调.

The jQuery throttle/debounce plugin is perfect for this. Use at_begin = false to execute the callback at the end.

var scrollEnded = $.debounce(500, false, function ()
{
    console.log('scroll ended');
});

$('#scrollableDiv').scroll(scrollEnded);

演示

这篇关于滚动结束后如何调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆