2012-10-26 24 views
2

我對頁面上的某個區域使用了「粘性頁腳」技術,該頁面上也有一個利用了附加項的導航欄。問題是數據偏移屬性需要根據粘滯頁腳的位置來更新 - 因此它不能被硬編碼。Twitter Bootstrap - 動態更新附加數據偏移屬性

如何以粘性頁腳所在的像素爲單位獲取值,並將該值傳遞給數據偏移屬性,以便知道何時粘貼本身?

任何幫助將不勝感激!

回答

2

我也正在修復導航欄取決於不能硬編碼到CSS的位置。不是因爲粘滯的頁腳,但只是空間上方的導航欄(當不固定)是動態的,但我想解決方案是類似的。

我正在使用JavaScript來修正/ unfix設置/取消設置適當的類dynamic取決於某些DOM元素是否在視口上可見。的方案如下:

  • 導航欄樣式爲position: absolute和空間含有它具有導航欄的靜態高度,所以不存在的定影時下面的內容的位置的變化,
  • 綁定的函數,間諜滾動和修正導航欄如果上述元素是不可見的,
  • 檢查,如果元件是通過比較其與視口的位置上的頂部位置的底部可見,
  • 修復/通過添加/移除每個自舉類拔去用戶滾動或更改窗口大小的時間。

Opa framework的代碼(轉換爲JS + jQuery的應該是直接作爲OPA的DOM庫只是簡單結合的jQuery):

// id of the element above the navbar, and the navbar 
logobar_id = "logo-bar"; 
navbar_id = "main-menu"; 
// hardcoded height of the navbar 
navbar_height_px = 30; 

client function distance() { 
    dom = #{logobar_id}; 

    // hardcoded height of the navbar 
    win = Dom.select_window(); 

    // position of the top of the viewport 
    scroll_visible = Dom.get_scroll_top(win); 

    // return the distance between of bottom of element above the navbar and the top of 
    dom_bottom = Dom.get_offset(dom).y_px + Dom.get_height(dom); 
    dom_bottom - scroll_visible; 
} 

dom = #{navbar_id}; 

private client function fixation() { 
    if (distance() <= 0) { 
    // TODO: remember if subnav is fixed, dont fix if fixed 
    Dom.add_class(dom, "navbar-fixed-top"); 
    Dom.remove_class(dom, "container"); 
    } else { 
    // TODO: remember if subnav is fixed, dont unfix if unfixed 
    Dom.remove_class(dom, "navbar-fixed-top"); 
    Dom.add_class(dom, "container"); 
    void; 
    } 
} 

// (un)fix when scroll 
private client function onscroll(_) { 
    fixation(); 
} 

// bind the `onscroll` handler for subnav when it is loaded 
private client function onready(_) { 
    _ = Dom.bind(Dom.select_window(), {scroll}, onscroll); 
    fixation(); 
} 

導航欄和所述導航欄本身上面的DOM元素:

<div class="container" id=#{logobar_id}> 
    My logo with dynamic content 
</div> 
<div class="container" style="height: {navbar_height_px}px; position: relative; top: 0px"> 
    <div style="position: absolute; top: 0px"> 
    <div class="navbar container" id=#{navbar_id} onready={onready}> 
     ... 
    </div> 
    </div> 
</div>