2017-04-20 88 views
0

目前我们已经实现了一个自定义滚动条,因为我们无法让Bootstraps滚动条正常工作。 的scrollspy:如何在点击锚点链接时忽略滚动,但是如果不滚动则听滚动?

$(window).scroll(function() { 
     var scroll = $(window).scrollTop(), 
      /*offsets = hashes.forEach(function (hash) { 
      return $(hash).offset().top; 
      }),*/ 
      last; 
     if (window.location.pathname === "/") { 
      if (scroll >= 20) { 
       $(".arrow").addClass("hidden"); 
      } else { 
       $(".arrow").removeClass("hidden"); 
      } 
      hashes.forEach(function (hash) { 
       if (hash === "#contact") { 
        if ($(hash).offset().top - navheight - 10 < scroll + 200) { 
         last = hash; 
        } 
       } else if ($(hash).offset().top - navheight - 10 < scroll) { 
        last = hash; 
       } 
      }); 

      hashes.forEach(function (hash) { 
       if (scroll >= ($(".notfooter").outerHeight() - 60 - $("#contact").outerHeight() - ($("#partners").outerHeight()/2))) { 
        $('li:has(a[href="#contact"])').addClass("testing"); 
        $('li:has(a[href="#partners"])').removeClass("testing"); 
       } else { 
        if (hash !== last) { 
         //console.log(hash + " not last hash"); 
         $('li:has(a[href="' + hash + '"])').removeClass("testing"); 
        } else if (hash === last) { 
         $('li:has(a[href="' + hash + '"])').addClass("testing"); 
        } 
       } 
      }); 
     } 
    }); 

的散列阵列仅仅是在它所有的锚链接的数组。

然后我们有一个叫scrollto的类,我们绑定一个click事件,然后将窗口滚动到相应的div。

$(".scrollto").on('click', function (event) { 
     // Make sure this.hash has a value before overriding default behavior 
     if (this.hash !== "") { 
     // Prevent default anchor click behavior 
     event.preventDefault(); 

     // Store hash 
     var hash = this.hash; 

     if (window.location.pathname !== "/") { 
      $.get("/indexcontent", function (data) { 
        $("#bodycontent").html(data); 
        history.pushState(null, null, "/"); 
        $('body').stop().animate({ 
         scrollTop: $(hash).offset().top - navheight 
        }, 800, function() { 
         history.pushState(null, null, ""); 
        }); 
       } 
      ); 
     } else { 
      $('body').stop().animate({ 
       scrollTop: $(hash).offset().top - navheight 
      }, 800, function() { 
       history.pushState(null, null, ""); 
      }); 
     } 
    } 
}); 

当点击一个链接它会先被标记为活动(类称为testing),我们将开始滚动到该分区。这是问题出现的地方,因为只要我们开始滚动$(window).scroll()事件触发器,并将继续从我们点击的链接中删除testing,并继续添加并从链接中移除它,当我们通过它们滚动页面时。

我想我可以做的是在scrollto click事件开始时解除滚动事件,然后在滚动完成时重新绑定它,但即使我在animate()的回调中做了这个,它仍会说它是在滚动实际完成之前完成并绑定的。

那么我应该怎么想呢?我对正确方向的绑定/解绑技巧有何推理?

回答

0

解决方案可能是.on和.off滚动事件处理程序。您可以在click处理程序的开始处关闭它,并在点击处理程序滚动动画结束后使用承诺或回调。

是的我的意思是绑定(jQuery .on())和解除绑定(jQuery .off())。

+0

与.unbinding和.binding不一样吗? –