---
title: "Bootstrap笔记之Affix"
author: "clxy"
date: "2013-09-19T23:32:53Z"
tags: ["CSS", "bootstrap", "jQuery"]
categories: ["Web前端"]
slug: "bootstrap-affix"
draft: false
lastmod: "2013-09-19T23:41:29Z"
id: 1944222
url: "https://clxy.iteye.com/blog/1944222"
---

升级Bootstrap 3时，顺便玩了下Affix——通常用在侧边导航条——这个控件，下面是一些坎坷和心得。（[详细的官方文档](http://getbootstrap.com/javascript/#affix)）

<span style="color:blue">**★：Top**</span>
  首先就是Top——高度，由于我页面上有固定的顶导航条（用Bootstrap的通常都会有），所以必须调整Top高度。
  通用的代码如下

```css

var navHeight = $('.navbar').outerHeight(true) + 10;
$sideBar.affix({
	offset: {
		top: navHeight
	}
});

```

  加上10px的余量是为了顶导航条和下面内容之间的间隙。其实也可以自动计算，只是太麻烦偷个懒。另外如果还用scrollspy的话（通常也都会用），也需要用上面的navHeight设置偏移量——offset。

```css

$body.scrollspy({
	target: '.bs-sidebar',
	offset: navHeight
});

```


  到这都OK，下面都是麻烦事。

<span style="color:blue">**★：Link点击后的位置偏移**</span>
  点击侧导航条时，页面上指定的Link会滚动过高，被顶导航条遮住。这个貌似不是Affix的问题，而是顶导航条固定位置的原因。需要用如下方式hack掉——copy自官方网站的css。

```css

/* Janky fix for preventing navbar from overlapping */
h1[id] {
  padding-top: 80px;
  margin-top: -45px;
}

```

  原理是比如想要35px的间隙，不能直接写35px。需要

top padding设置成80px，防止顶导航条遮挡。
然后再设置top margin为-45px，以达到35px的效果。
折腾吧？

<span style="color:blue">**★：滚动页面时尺寸会改变**</span>
  还有个问题就是滚动页面，当侧边导航条浮起时会改变尺寸。
  参考了官网的源码，最终也没有找到理想的解决办法。我猜测原因在于官网是两边留余白的方式，这种方式下，affix的宽度只有在页面尺寸变化到达BS3的screen阈值时才会跟着变化，相对稳定。我自己的则是100%伸展的布局。
  我找到折衷的办法是写死affix尺寸，让它和浮起时尺寸相同。但这样就导致affix无法响应页面宽度细微的变化！

```css

/* Show and affix the side nav when space allows it */
@media screen and (min-width: 992px) {
	...
	/* Widen the fixed sidebar */
	.bs-sidebar,.bs-sidebar.affix,.bs-sidebar.affix-bottom {
		width: 223px;
	}
	...
}

@media screen and (min-width: 1200px) {
	/* Widen the fixed sidebar again */
	.bs-sidebar,.bs-sidebar.affix-bottom,.bs-sidebar.affix {
		width: 299px;
	}
}
```

“.bs-sidebar,”是追加的内容，即affix的非浮起状态尺寸。

  如果有哪位知道更好的解决方案，还望赐教。