首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Twitter Bootstrap -动态更新Affix Data-Offset属性

Twitter Bootstrap -动态更新Affix Data-Offset属性
EN

Stack Overflow用户
提问于 2012-10-26 09:15:41
回答 1查看 1.1K关注 0票数 2

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

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

任何帮助都将不胜感激!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-10-26 17:49:49

我还修复了导航栏的位置,不能硬编码到css。这不是因为一个粘性的页脚,而是导航栏上方的空格(当没有固定时)是动态的,但我认为解决方案是相似的。

我使用JavaScript通过动态地设置/取消设置适当的类来修复/取消修复,这取决于某些DOM元素是否在视区中可见。该计划的内容如下:

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

Opa framework中的代码(转换为JS+jQuery应该很简单,因为Opa的DOM库只是简单地绑定到jQuery):

代码语言:javascript
复制
// 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元素:

代码语言:javascript
复制
<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>
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13079529

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档