如何在jQuery中使用此函数

时间:2012-11-07 21:29:05

标签: javascript jquery function

我有以下jQuery函数,它应该检测元素首次滚动到页面上的视图时:

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

我的思绪今天糊涂了......我怎么能用这个功能?

假设我想检测何时进入$('.guardrail360')

3 个答案:

答案 0 :(得分:2)

好像你需要绑定滚动事件并在事件触发时进行检测。

$(window).scroll(function () { 
  isScrolledIntoView('.guardrail360');
});

答案 1 :(得分:2)

有几种方法可以做到这一点。如果您关注用户体验和/或性能,请不要使用天真的window.scroll实现。

  

将处理程序附加到窗口滚动是一个非常非常糟糕的主意   事件。根据浏览器的不同,滚动事件可以激活很多   将代码放入滚动回调将减慢任何尝试   滚动页面(不是一个好主意)。任何性能下降   因此,滚动处理程序只会影响性能   整体滚动。相反,使用某种形式的a更好   计时器检查每X毫秒或附加滚动事件和   只在延迟后运行你的代码(或者甚至在给定数量的代码之后运行   执行 - 然后延迟)。

     

-John Resig,jQuery的创建者,ejohn.org

方法1:setInterval

首先,有一种使用计时器的天真方法:

var $el = $('.guardrail360');

var timer = setInterval(function() {
    if (isScrolledIntoView($el)) {
        // do stuff

        // to run this block only once, simply uncomment the next line:
        //clearInterval(timer);
    }
}, 150);

方法2:window.scroll事件

然后使用滚动事件有一些微不足道但又疯狂低效的方式(取决于浏览器,滚动事件每秒会触发数百次,所以你不想运行很多这里的代码,尤其不是触发浏览器重排/重绘的代码。

有没有访问过一个网页,滚动页面感觉迟钝和紧张?这通常是由像这样的一段代码引起的:

var $el = $('.guardrail360');

$(window).on('scroll', function() {
    if (isScrolledIntoView($el)) {
        // do stuff
    }
});

方法3:两全其美

John Resig在aforementioned blog post中提出的针对高流量网站的漂亮混合方法:

var $el = $('.guardrail360'),
    didScroll = false;

$(window).scroll(function() {
    didScroll = true;
});

var timer = setInterval(function() {
    if ( didScroll ) {
        didScroll = false;
        if (isScrolledIntoView($el)) {
            // do stuff

            // to run this block only once, simply uncomment the next line:
            //clearInterval(timer);
        }
    }
}, 250);

方法4:节流/去噪

限制(调用之间的最小N毫秒)或去抖动(每个'突发'只有一次调用)模式也可用于有效地限制内部代码执行的速率。假设您正在使用Ben Alman's jQuery throttle/debounce plugin,代码如下所示:

var $el = $('.guardrail360');

// Throttling
$(window).on('scroll', $.throttle( 250, function(){
    if (isScrolledIntoView($el)) {
        // do stuff
    }
}));

// Debouncing
$(window).on('scroll', $.debounce( 250, function(){
    if (isScrolledIntoView($el)) {
        // do stuff
    }
}));

(请注意,去抖动与其他实现略有不同,但有时可能是您想要的,具体取决于您的用户体验场景)

答案 2 :(得分:0)

if ( isScrolledIntoView('.guardrail360') ) {

}

根据其他答案的建议,您应该使用$(window).scroll()上的行为。另外,为了让元素第一次滚动到视图中运行if语句,我为你创建了这个run_once函数:

$('window').on('scroll', function() {

    if ( isScrolledIntoView('.guardrail360') ) run_once(function() {
            // ...
    });

});

function run_once( callback ) {

    var done = false;

    return function() {

        if ( !done ) {

            done = true;

            return callback.apply( this, arguments );

        }

    };

}
相关问题