2017-04-20 54 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不一樣嗎? –