在功能上火Ajax调用每个条件检查结合window.scroll只有一次 [英] fire ajax call in function binding window.scroll only once per conditional check

查看:114
本文介绍了在功能上火Ajax调用每个条件检查结合window.scroll只有一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个小提琴这要是有针对性的检测 DIV 是在视口中。但是,如果我想在DOM元素是在视口中(而非多次)火只有一个Ajax调用。我怎么能做到这一点?

I am having this fiddle which detects if targeted div is in the viewport. However if I want to fire only one ajax call when the DOM element is in the viewport (instead of multiple times). How could I make this happen?

if( isTargetVisble() ) { // if target element is visible on screen after DOM loaded
    $('.log').html('<div class="alert alert-success">target element is visible on screen</div>'); // log info
    alert('this is going to be the ajax call')
} else {
    $('.log').html('<div class="alert">target element is not visible on screen</div>'); // log info
}

据发射多个警报()现在,因为它绑定到 window.scroll 。我怎么可以只火一把,当它成为可见?

It is firing multiple alert() right now as it is binding to window.scroll. How could I just fire one when it becomes visible?

推荐答案

跟踪目标的可视状态的变量。在每个滚动,比较的新值isTargetVisble()与旧的。

Keep track of the visible state of the target with a variable. On each scroll, compare the new value of isTargetVisble() with the old.

var _alreadyVisible = false;
$(window).scroll(function(){ // bind window scroll event
    if( $('.target').length > 0 ) { // if target element exists in DOM
        if( isTargetVisble() ) { // if target element is visible on screen after DOM loaded
            if(_alreadyVisible){
                //ignore the scroll
            } else {
                //the target just became visible
                _alreadyVisible = true;
                console.log('target became visible')
                $('.log').html('<div class="alert alert-success">target element is visible on screen</div>'); // log info
            }
        } else {
            if(_alreadyVisible){
                //the target was just hidden
                _alreadyVisible = false;
                $('.log').html('<div class="alert">target element is not visible on screen</div>'); // log info
                console.log('target became invisible')
            } else {
                //ignore
            }
        }
    }
});

请参阅此小提琴(带来了F12控制台并注意只有一个登录目标改变时,可见性,而不是每次滚动)

See this fiddle (bring up the console with F12 and notice how there is only a log when the target changes visibility, not on every scroll)

这篇关于在功能上火Ajax调用每个条件检查结合window.scroll只有一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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