如何检测页面滚动到jQuery中的某个点? [英] How to detect page scroll to a certain point in jQuery?

查看:65
本文介绍了如何检测页面滚动到jQuery中的某个点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象这是我的页面:

<p>hello</p>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<p class="myPara">My Paragraph</p>

当用户向下滚动到类别为"myPara"的段落而不是之前时,该如何提示消息?

How can I alert a message when the user has scrolled down to the paragraph with the class "myPara" and not before then?

推荐答案

怎么样:

var target = $(".myPara").offset().top;
var interval = setInterval(function() {
    if ($(window).scrollTop() >= target) {
        alert("made it!");
        clearInterval(interval);
    }
}, 250);

这里是一个示例: http://jsfiddle.net/andrewwhitaker/24M3n/1/

您可能会想将事件处理程序附加到窗口滚动事件,但是 John Resig建议(向下滚动至最佳做法").

You might be tempted to attach an event handler to the window scroll event, but John Resig advises against it (Scroll down to "Best Practices").

更新: @AbdulJabbarWebBestow指出,这可能是每250毫秒不必要地运行一个功能的坏主意.这是一个更新的示例,在用户第一次滚动后250ms内仅运行一次:

Update: As @AbdulJabbarWebBestow points out, it might be a bad idea to unnecessarily run a function every 250ms. Here's an updated example that only runs once, 250ms after the first time a user scrolls:

var target = $(".mypara").offset().top,
    timeout = null;

$(window).scroll(function () {
    if (!timeout) {
        timeout = setTimeout(function () {
            console.log('scroll');            
            clearTimeout(timeout);
            timeout = null;
            if ($(window).scrollTop() >= target) {
                alert('made it');
            }
        }, 250);
    }
});

示例: http://jsfiddle.net/24M3n/858/

这篇关于如何检测页面滚动到jQuery中的某个点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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