当我到达页面顶部时,如何启动JavaScript或jQuery事件? [英] How can I launch a JavaScript or jQuery event when I reach the top of my page?

查看:65
本文介绍了当我到达页面顶部时,如何启动JavaScript或jQuery事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题,但我找不到解决方案...
我只是想在我向上滚动页面时启动一个事件(执行一个方法)并且我触摸顶部它的。我在我的页面中使用JavaScript和jQuery。提前致谢!

I have a simple problem, but I can't find the solution ... I just want to launch an event (which execute a method) when I scroll my page up and I "touch" the top of it. I'm using JavaScript and jQuery in my page. Thanks in advance !

推荐答案

您应该为此目的使用滚动事件:

You should use the scroll event for that purpose:

$(window).scroll(function() {
    if ($(this).scrollTop() == 0) {
        //Do whatever you want to do
    }
});

你应该注意的一件事是,当某人连续滚动到顶部时,偶数会被解雇只有在命中顶部时才需要它,为此你可以将事件处理程序定义为函数,并将最后一个scrolltop值放入函数局部变量中。

One thing you should notice is that this way when somebody scrolls to top continuously the even will be fired although you only want it once the top is hit, for this you can define the event handler as a function and put the last scrolltop value into a function local variable.

$(window).scroll(handleHitTop);

function handleHitTop(event) {
    var currentScrollTopValue = $(this).scrollTop();

    if (handleHitTop.lastTop === undefined) {
        handleHitTop.lastTop = currentScrollTopValue ;

        return;
    }

    if (handleHitTop.lastTop == 0 && currentScrollTopValue == 0) {
        return;
    }

    handleHitTop.lastTop = currentScrollTopValue;

    if (handleHitTop.lastTop == 0) {
        //Call your event here
    }
}

这篇关于当我到达页面顶部时,如何启动JavaScript或jQuery事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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