JQuery Scroll detection fire once

假装没事ソ 提交于 2019-11-30 17:40:34

问题


I have a small piece of JQuery designed to collapse my header, change its dimensions, and then stick it to the side of the screen. It all works apart from one part, the height 'toggle' function fires every time the user scrolls, which gets really irritating.

Is there a way I can detect scroll only once OR toggle only once?

$(window).scroll(function () {
var width = $(document).width() - 205;
var height = $(document).height();
  $('#me').animate({
    marginLeft: width,
    width: '22px',
    height: 'toggle',
    borderLeftWidth: "10px",
    borderRightWidth: "10px"    
  }, 1000, function() {
    $("#me:first").css("margin-top","-90px");
    var div = $('#me');
    $('#me h1').css("font-size","30px");
    var start = $(div).offset().top;
    $(div).css("height", height);
    $.event.add(window, "scroll", function() {
        var p = $(window).scrollTop();
        $(div).css('position',((p)>start) ? 'fixed' : 'static');
        $(div).css('top',((p)>start) ? '0px' : '');
    });
  });
});

回答1:


look at jquery's one() functionality http://api.jquery.com/one/

It will only fire once and then promptly remove itself..




回答2:


use a flag to check it is first time or not

var doHeightToggle=true;


$.event.add(window, "scroll", function() {
   if(doHeightToggle)
   {
        var p = $(window).scrollTop();
        $(div).css('position',((p)>start) ? 'fixed' : 'static');
        $(div).css('top',((p)>start) ? '0px' : '');
        doHeightToggle = false;
   } 
});


来源:https://stackoverflow.com/questions/12731795/jquery-scroll-detection-fire-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!