Javascript 中断jQuery';s打开(“滚动”)

Javascript 中断jQuery';s打开(“滚动”),javascript,jquery,events,scroll,Javascript,Jquery,Events,Scroll,我找不到更好的标题来描述我的问题 在一个单页站点上,我使用此脚本检测用户正在阅读的位置,并更新到菜单: $(document).on("load scroll",function(e) { var scroll_top = $(document).scrollTop(); var home = $('#home').position().top; var references = $('#references').position().top; var contact = $('

我找不到更好的标题来描述我的问题

在一个单页站点上,我使用此脚本检测用户正在阅读的位置,并更新到菜单:

$(document).on("load scroll",function(e) {
  var scroll_top = $(document).scrollTop();
  var home = $('#home').position().top;
  var references = $('#references').position().top;
  var contact = $('#contact').position().top;
  if ( scroll_top < references || scroll_top == 0)
        {
            $('header nav a').removeClass('active');
            $('header nav a:first-of-type').addClass('active');
        } else if ( scroll_top > references && scroll_top < contact) {
            $('header nav a').removeClass('active');
            $('header nav a:nth-child(2)').addClass('active');
        } else if( scroll_top > contact) {
            $('header nav a').removeClass('active');
            $('header nav a:nth-child(3)').addClass('active');
        }
});
我的问题是:当用户单击导航中的一个链接时,我不希望站点表现得像用户手动滚动一样。因此,我不希望“途中”的每个链接都使类
处于活动状态
,而只希望导航中的目标链接


我尝试在单击链接时设置一个全局变量,并将此条件添加到“滚动”侦听器中,但不起作用。

用户单击链接并在滚动完成后将其删除时,可以将数据属性添加到
body
或其他内容,然后在事件处理程序中检查
body
的数据属性是否具有正确的值如果单击特定元素,是否尝试从函数返回?@JordanDoyle:好主意,我尝试了。现在,在任何情况下都不会追加该类。我还尝试向nav元素添加一个类。结果:加载时,当用户滚动时,不会添加该类。但是,当平滑滚动由
scrollToAnchor
函数触发时,会追加该类!显然,这似乎是有区别的@coder006:我也试过,但没有任何效果。
$(function() {
  // scroll handler
  var scrollToAnchor = function( id ) {
    // grab the element to scroll to based on the name
    var elem = $("a[name='"+ id +"']");
    // if that didn't work, look for an element with our ID
    if ( typeof( elem.offset() ) === "undefined" ) {
      elem = $("#"+id);
    }
    // if the destination element exists
    if ( typeof( elem.offset() ) !== "undefined" ) {
      // do the scroll
      scroll_animate = false;
      $('html, body').animate({scrollTop:elem.offset().top}, {duration:1000});
      scroll_animate =  true;
    }
  };
  // bind to click event
  $("a").click(function( event ) {
    // only do this if it's an anchor link
    if ( $(this).attr("href").match("#") ) {
      // cancel default event propagation
      event.preventDefault();
      // scroll to the location
      var href = $(this).attr('href').replace('#', '')
      scrollToAnchor( href );
    }
  });
});