jQuery-滚动超过x像素后执行功能 [英] jquery - carry out function after scroll past x pixels

查看:122
本文介绍了jQuery-滚动超过x像素后执行功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在自己的网站上进行了一次导航,定位绝对.

I've made a nav on my site which is absolute positioned.

我制作了一个班级,将其固定在屏幕顶部.

I've made a class to make this fixed to the top of the screen.

我要找出的是在窗口向下滚动x向下滚动页面像素数(本例为500 px)后如何执行功能(本例为toggleClass)

What I'm trying to find out is how to carry out a function (toggleClass in this instance) after the windows has been scrolled x amount of pixels down the page (500 px in this instance)

推荐答案

过程为:

  • 收听滚动事件以检测用户滚动时的滚动位置
  • 从页面顶部计算元素的位置,或确定距页面顶部的固定距离(在您的示例中为500px)
  • 滚动位置大于触发位置时,执行功能.如果只希望函数触发一次,请删除函数中的滚动侦听器.

假设使用jQuery,则如下所示:

Assuming jQuery, something like this:

$(window).on('scroll', function() {
    scrollPosition = $(this).scrollTop();
    if (scrollPosition >= 500) {
        // If the function is only supposed to fire once
        $(this).off('scroll');

        // Other function stuff here...
    }
});

这篇关于jQuery-滚动超过x像素后执行功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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