如何在特定滚动高度期间仅调用一次函数?

时间:2014-10-21 00:54:37

标签: javascript jquery

我的网页底部有一张地图,当用户向下滚动到地图时,我想要删除google标记和特定时间。我已经有了这个工作。问题是它一直在调用函数,我怎么只调用它一次?

这是我现在的JS代码,我试图找出错误:

      $(window).scroll(function () {

     if ($(window).scrollTop() >= $(document).height() - $(window).height() - 300 && 
        $(window).scrollTop() <= $(document).height() - $(window).height() - 200
        ) {

        var dropOnlyOnce = (function(){  

            dropped = false;
            if (dropped == false) {
                dropMarker(); // this is the function I'm calling
            }
            dropped = true;

        })();

     } 

  });

如何让它工作或如何只调用一次dropMarker函数?

3 个答案:

答案 0 :(得分:2)

您可以在调用函数后删除侦听器:

$(window).on('scroll', function(e) {
  if( ...window at scrollTop ) {

    $(window).off('scroll')
    .... Drop your pin
  }
})

Esteban Felix的评论提出了一个很好的观点。这将删除所有滚动处理程序。如果那不适合你,你可以将函数移到处理程序之外,只删除它:

var dropPinOnce = function() {
  if( ... window at correct scrollTop ) {
    ... Drop pin here ...
    $(window).off('scroll', dropPinOnce)
}

$(window).on('scroll', dropPinOnce)

答案 1 :(得分:1)

尝试

var callbacks = $.Callbacks("once")
, dropMarker = function() {
    // do stuff
}; 
callbacks.add(dropMarker);

$(window).scroll(function () {

     if ($(window).scrollTop() >= $(document).height() - $(window).height() - 300 && 
        $(window).scrollTop() <= $(document).height() - $(window).height() - 200
        ) {    
        var dropOnlyOnce = (function(){      
            dropped = false;
            if (dropped == false) {
                callbacks.fire() // call `dropMarker` "once"
            }
            dropped = true;   
        })();   
     }    
  });

jQuery.Callbacks at&#34;可能的旗帜&#34; - &GT; &#34;一次&#34;

&#13;
&#13;
var callbacks = $.Callbacks("once")
, dropMarker = function() {
    console.log(123)
}; 

callbacks.add(dropMarker);

$(window).scroll(function () {

     if ($(window).scrollTop() >= $(document).height() - $(window).height() - 300 && 
        $(window).scrollTop() <= $(document).height() - $(window).height() - 200
        ) {

        var dropOnlyOnce = (function(){  

            dropped = false;
            if (dropped == false) {
               // dropMarker(); // this is the function I'm calling
                callbacks.fire()
            }
            dropped = true;

        })();

     } 

  });
&#13;
div {
  height : 500px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>abc</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

如果您在满足条件后解除绑定,那么您的功能实际上只会被调用一次。

$(window).scroll(function callOnceOnScroll() {
    var $window = $(window),
        $document = $(document);
    if ($window.scrollTop() >= $document.height() - $window.height() - 300 &&
        $window.scrollTop() <= $document.height() - $window.height() - 200) {

        $window.off('scroll', callOnceOnScroll);
        dropMarker(); // this is the function I'm calling
    }

});