2012-08-29 94 views
9

我有我想要'子導航'的網站。因此,當您滾動到部分時,其工具欄將粘貼在主工具欄下方。我有這個工作,但我無法改變初始化後的頂部偏移量。該文件說:Twitter引導更改詞綴偏移

affix('refresh')

When using affix in conjunction with adding or removing of elements from the DOM, you'll want to call the refresh method:

但是當我嘗試這樣我得到:

Uncaught TypeError: Object # has no method 'refresh'

這裏是我的代碼:

$(function() { 
    $('.sec-nav').addClass("affix-top"); 
    var adjustNavs = function (first) { 
     $('.sec-nav').each(function(){ 
      var $p = $(this).closest('.sec'); 
      var $$ = $p.prevAll('.sec'); 
      console.log($$); 
      var h = 0; 
      $$.each(function() { h+=$(this).outerHeight();}); 
      console.log(h); 

      if (first) { 
       $(this).affix({offset: {top: h}}); 
      } else { 
       $(this).data('affix', {b: {options: {offset:{top: h}}}}); 
       console.log(this); 
       $(this).affix('refresh') 
      } 

     }); 
    } 
    adjustNavs(true); 
    $('.sec').bind('DOMSubtreeModified', function() { 
     adjustNavs(); 
    }); 
}); 

我試過的

   $(this).data('affix', {b: {options: {offset:{top: h}}}}); 
不同變化

包括:

   $(this).affix({offset: {top: h}}); 

我無法獲得要更改的偏移量。你如何改變詞綴插件的偏移量?謝謝。

+1

您可以粘貼HTML塊嗎?很難說不然...如果你嘗試用'$('。sec-nav')。'affix();'替換'$('。sec-nav')。addClass(「affix-top」);''這些幫助有用?或者你已經在'.sec-nav'上獲得了'data-spy =「affix」'屬性? –

回答

20

我想通了。代替的動態更新的偏移,我偏移值改變爲一個函數:

$(function() { 
    $('.sec-nav').addClass("affix-top").each(function(){ 
     var $self = $(this); 
     var offsetFn = function() { 
      var $p = $self.closest('.sec'); 
      var $$ = $p.prevAll('.sec'); 
      var h = 0; 
      $$.each(function() { h+=$(this).outerHeight();}); 
      return h; 
     } 
     $self.affix({offset: {top: offsetFn}}); 
    }); 
}); 

現在,當由於DOM操作或窗口調整大小的截面的變化,使偏移全自動改變由於函數返回值變更。

+0

絕妙的主意! – viniciusnz

+2

你可以提供使用的HTML,或者一個工作的例子嗎?我正在嘗試將此工作應用到現有的代碼中,但我不知道.sec是什麼。 – davecave

+1

試圖在窗口上調整大小'$('。myMeny')。affix({offset:{top:myOffet}});'但沒有工作,值沒有變化 – sreginogemoh

2

我簡化了Fatmuemoo對於更基本的情況的答案: 我的主頁的導航欄(默認引導程序#masthead)位於ID爲#bg的大背景滑塊下方。滑塊的高度隨着3個css斷點而變化。我們只是將#masthead的偏移量設置爲等於滑塊的高度。簡單!

$('header#masthead').affix({ //sticky header at bottom of bg 
     offset: { 
      top: function(){return $("#bg").outerHeight();} 
     } 
    }); 
+0

感謝,簡單而高效,效果很好,很容易創建你需要的所有元素的總和。 – EPurpl3