每次条件检查时,只在函数绑定window.scroll中触发一次ajax调用

时间:2014-06-24 18:47:36

标签: javascript jquery ajax

我正在使用此fiddle来检测目标div是否在视口中。但是,如果我想在DOM元素位于视口中时仅触发一个ajax调用(而不是多次)。我怎么能做到这一点?

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
}

它现在正在触发多个alert(),因为它绑定到window.scroll。当它变得可见时我怎么才能开火?

1 个答案:

答案 0 :(得分:0)

使用变量跟踪目标的可见状态。在每个滚动条上,将isTargetVisble()的新值与旧值进行比较。

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
            }
        }
    }
});

请参阅此fiddle(使用F12调出控制台,注意目标更改可见性时只有日志,而不是每次滚动时)