【问题标题】:Twitter Bootstrap - Update Affix Data-Offset attribute on the flyTwitter Bootstrap - 即时更新 Affix Data-Offset 属性
【发布时间】:2012-10-16 06:46:46
【问题描述】:

我正在对页面上的一个区域使用“粘性页脚”技术,该区域也有一个使用词缀的导航栏。问题是 data-offset 属性需要根据粘性页脚的位置进行更新 - 因此它不能被硬编码。

如何获取粘性页脚所在位置的像素值,并将该值传递给 data-offset 属性,以便它知道何时粘贴自己?

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript jquery twitter-bootstrap sticky-footer


    【解决方案1】:

    我还在修复导航栏,具体取决于无法硬编码到 css 中的位置。不是因为页脚粘滞,而是导航栏上方的空间(未固定时)是动态的,但我想解决方案是相似的。

    我正在使用 JavaScript 通过动态设置/取消设置适当的类来修复/取消修复,具体取决于某些 DOM 元素是否在视口上可见。方案如下:

    • navbar 样式为position: absolute 并且包含它的空间具有navbar 的静态高度,因此在修复时不会改变下方内容的位置,
    • 如果上面的元素不可见,则绑定监视滚动和修复导航栏的函数,
    • 通过比较元素的底部位置和视口位置的顶部来检查元素是否可见,
    • 通过在每次用户滚动或更改窗口大小时添加/删除引导类来修复/取消修复。

    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>
    

    【讨论】:

      猜你喜欢
      • 2013-09-11
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 2016-07-08
      相关资源
      最近更新 更多