为什么我的平滑滚动偏移功能仅在第二次单击时起作用?

时间:2019-04-17 23:52:02

标签: jquery

我有一个功能,可以平滑滚动到锚点并偏移导航栏的高度。一切正常,可以平滑滚动到锚点,但是在第一次单击时不会偏移。当我第二次单击链接时,它将抵消。您可以在这里看到我的意思:http://madenicely.com/inovar/what-we-do/#services,然后单击任何“我们的服务”悬停框。

我尝试在论坛中寻找答案,但是找不到我能理解的任何东西。

这是我正在使用的代码:

jQuery(document).ready(function(){
  // Add smooth scrolling to all links
  jQuery("a").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;

      //Get Header Height
     var headerHeight = jQuery(".navbar").height();

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      jQuery('html, body').stop().animate({
        scrollTop: jQuery(hash).offset().top - headerHeight
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});

我希望窗口滚动到锚点,并使其偏移导航栏的高度。

0 个答案:

没有答案
相关问题