1

我正在尝试复制这个: http: //twitter.github.com/bootstrap/base-css.html#typography(顶部有标签:|排版|代码表|表单|按钮|Glyphicons的图标|)。我想复制同样的快速作用效果。

我想让这个 div 做同样的事情:

#panel {
    margin: auto;
    border-bottom: 1px solid rgba(0,0,0,.6);
    border-top: 0;
    box-shadow: 0 1px rgba(0,0,0,.1),
    1px 0 rgba(0,0,0,.1),
    -1px 0 rgba(0,0,0,.1),
    0 -1px rgb(255,255,255) inset,
    0 1px 2px rgba(0,0,0,.2) inset,
    1px 0 rgb(255,255,255) inset,
    -1px 0 rgb(255,255,255) inset;
    background: #E8E8E8;    
    width: 75%;
    -webkit-border-bottom-left-radius: 5px;
    -moz-border-radius-bottomleft: 5px;
    -moz-border-radius-bottomright: 5px;
    -webkit-border-bottom-right-radius: 5px;
    color: rgba(0,0,0,.7);
    text-shadow: 0 1px white;
    padding: 2px 0px 2px 8px;
    margin-top: -149px;
    text-align: left;
    font-size: 11px;
}

在我的网站上:http: //www.bobbaxtrade.com

谢谢 :)

4

3 回答 3

2

我在这里创建了 jsFiddle:http: //jsfiddle.net/cBk7q/

因此,您需要在您的 CSS 规则中添加一个类,以使您的 div 在窗口顶部保持静态:

.fixed {
    position: fixed;
    top: 0;
    left: 0;
}

然后,添加一个 jQuery 函数来绑定滚动事件并在到达所需位置时添加固定类:

<script type="text/javascript">
    var $mydiv = $("#mydiv"),
        origTop = $("#mydiv").position().top;

    $(window).scroll(function(e) {
        if( document.body.scrollTop > origTop) {
            console.log($mydiv.hasClass('fixed'));
            $mydiv.addClass("fixed");
        }
        else {
            console.log('c ' + (document.body.scrollTop > origTop));
            $mydiv.removeClass("fixed");
        }
    });
</script>
于 2012-05-05T18:03:06.300 回答
1

Bootstrap 网站向您解释了如何使用此功能

如果您使用的是引导程序,则可以使用 CSS 类navbar-fixed-top来获取此行为:

<div id="panel" class="navbar navbar-fixed-top">
  ...
</div>

如果你想要效果,导航栏只有在滚动后才变得固定,你需要navbar-fixed-top使用一些 JavaScript 动态添加类(取自LessCSS)。

假设你有一些 HTML

<!-- some content -->
<div id ="panel">
  …
</div>
<!-- enough other content to make the document scroll -->

和一些 CSS

.navbar-fixed-top {
  position: fixed;
  top: 0;
  left: 0;
}

然后下面的 JS 会给你请求的行为。

var docked = false;
var menu = document.getElementById('panel');
var init = menu.offsetTop;

function scrollTop() {
  return document.body.scrollTop || document.documentElement.scrollTop;
}

window.onscroll = function () {
  if (!docked && (menu.offsetTop - scrollTop() < 0)) {
    menu.style.top = 0;
    menu.className = 'navbar-fixed-top';
    docked = true;
  } else if (docked && scrollTop() <= init) {
    menu.style.top = init + 'px';
    menu.className = menu.className.replace('navbar-fixed-top', '');
    docked = false;
  }
};

此示例适用于 Firefox、Chrome、Opera 和 Safari。Internet Explorer 需要一种解决方法。

于 2012-05-05T18:13:36.560 回答
0

If you're using jQuery, try https://github.com/bigspotteddog/ScrollToFixed. Basic usage would be:

$(document).ready(function() {
    $('#panel').scrollToFixed();
});

... however, see the link for options (e.g. allowing for footer panels when the user scrolls down, etc).

于 2012-05-05T18:26:26.427 回答