jquery 等待滚动完成然后执行函数

jquery wait till scrolling is finished then execute function

当我单击导航按钮时,页面会滚动到顶部,然后应该会打开菜单。

目前我必须点击两次才能打开。

$("#nav-toggle").click(function() {
$("html, body").animate({ scrollTop: 0 }, 0);
 this.classList.toggle( "active" );
  $("#menu").toggleClass("open");
});

$( window ).scroll(function() {
 $( "#nav-toggle" ).removeClass("active");
 $( "#menu" ).removeClass("open");
});

jsfiddle

感谢您的帮助

动画有完整方法

http://api.jquery.com/animate/

观看示例:

$( "#clickme" ).click(function() {
  $( "#book" ).animate({
    width: [ "toggle", "swing" ],
    height: [ "toggle", "swing" ],
    opacity: "toggle"
  }, 5000, "linear", function() {
    $( this ).after( "<div>Animation complete.</div>" );
  });
});

试试这个。它会检查您是否已经在顶部,如果是,则不会删除您需要查看菜单的 类:

$("#nav-toggle").click(function() {
    $("html, body").animate({ scrollTop: 0 }, 0);
  $(this).toggleClass( "active" );
  $("#menu").toggleClass("open");
});

$( window ).scroll(function() {
    if($(window).scrollTop() == 0 || $(window).scrollTop() == $(document).height()- $(window).height()) {
   // do nothing
}
    else
  {
    // remove the classes
    $( "#nav-toggle" ).removeClass("active");
    $( "#menu" ).removeClass("open");
  }
});

请看下面修改后的代码:

https://jsfiddle.net/m0v2aahp/12/

  startScrollEvent();

$("#nav-toggle").click(function() {
  stopScrollEvent();
  $("html, body").animate({
    scrollTop: 0
  }, "fast", function() {

    $("#menu").addClass("open");
    $("#nav-toggle").addClass("active");
    setTimeout(function() {
      startScrollEvent();
    }, 200);
  });
});

function startScrollEvent() {
  $(window).on("scroll.myscrollevent", function() {
    $("#nav-toggle").removeClass("active");
    $("#menu").removeClass("open");
  });
}

function stopScrollEvent() {
  $(window).off("scroll.myscrollevent");
}

这里我们启动和停止滚动事件侦听器(实际上是删除在 animation 的回调中添加的 classes)以实现我们添加 activeopen class。