在功能上火Ajax调用每个条件检查结合window.scroll只有一次条件、功能、scroll、Ajax

2023-09-10 22:18:42 作者:醉枕江山

我有这个小提琴这要是有针对性的检测 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)