使用Twitter Bootstrap基于滚动位置更新DOM?

时间:2012-02-04 01:04:02

标签: dom position twitter-bootstrap

如果您查看此页面:http://twitter.github.com/bootstrap/components.html

注意子菜单及其位置。现在向下滚动 - 注意它是如何变化的?我假设他们使用scrollspy插件实现了它,但我似乎无法弄清楚如何做到这一点,我所能做的就是更新哪个列表元素具有活动类。

非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:0)

您可以在application.js文件中找到这段代码,它看起来并不像下载中那样。它可用here ...有趣的是标题注释

// NOTICE!! DO NOT USE ANY OF THIS JAVASCRIPT
// IT'S ALL JUST JUNK FOR OUR DOCS!
// ++++++++++++++++++++++++++++++++++++++++++

这是我认为繁重的部分......没有经过测试,只是逐步完成Chrome中的代码

// fix sub nav on scroll
var $win = $(window)
  , $nav = $('.subnav')
  , navTop = $('.subnav').length && $('.subnav').offset().top - 40
  , isFixed = 0

processScroll()

$win.on('scroll', processScroll)

function processScroll() {
  var i, scrollTop = $win.scrollTop()
  if (scrollTop >= navTop && !isFixed) {
    isFixed = 1
    $nav.addClass('subnav-fixed')
  } else if (scrollTop <= navTop && isFixed) {
    isFixed = 0
    $nav.removeClass('subnav-fixed')
  }
}

答案 1 :(得分:0)

CCBlackburn的答案很接近,但缺少必要的样式表。对于后代我也包括了javascript。无论如何,我使用以下方法使用它:

的Javascript

// fix sub nav on scroll
var $win = $(window)
  , $nav = $('.subnav')
  , navTop = $('.subnav').length && $('.subnav').offset().top - 40
  , isFixed = 0

processScroll()

// hack sad times - holdover until rewrite for 2.1
$nav.on('click', function () {
  if (!isFixed) setTimeout(function () {  $win.scrollTop($win.scrollTop() - 47) }, 10)
})

$win.on('scroll', processScroll)

function processScroll() {
  var i, scrollTop = $win.scrollTop()
  if (scrollTop >= navTop && !isFixed) {
    isFixed = 1
    $nav.addClass('subnav-fixed')
  } else if (scrollTop <= navTop && isFixed) {
    isFixed = 0
    $nav.removeClass('subnav-fixed')
  }
}

样式表

/* Fixed subnav on scroll, but only for 980px and up (sorry IE!) */
@media (min-width: 980px) {
  .subnav-fixed {
    position: fixed;
    top: 40px;
    left: 0;
    right: 0;
    z-index: 1020; /* 10 less than .navbar-fixed to prevent any overlap */
    border-color: #d5d5d5;
    border-width: 0 0 1px; /* drop the border on the fixed edges */
    -webkit-border-radius: 0;
       -moz-border-radius: 0;
            border-radius: 0;
    -webkit-box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);
       -moz-box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);
            box-shadow: inset 0 1px 0 #fff, 0 1px 5px rgba(0,0,0,.1);
    filter: progid:DXImageTransform.Microsoft.gradient(enabled=false); /* IE6-9 */
  }
  .subnav-fixed .nav {
    width: 938px;
    margin: 0 auto;
    padding: 0 1px;
  }
  .subnav .nav > li:first-child > a,
  .subnav .nav > li:first-child > a:hover {
    -webkit-border-radius: 0;
       -moz-border-radius: 0;
            border-radius: 0;
  }
}

/* LARGE DESKTOP SCREENS */
@media (min-width: 1210px) {

  /* Update subnav container */
  .subnav-fixed .nav {
    width: 1168px; /* 2px less to account for left/right borders being removed when in fixed mode */
  }

}