javascript - 有没有办法在我的网站上制作一个向下滚动时位于顶部的 div?

标签 javascript css xhtml prototypejs

我正在尝试复制这个: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

谢谢:)

最佳答案

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

因此,您需要向您的 css 规则添加一个类,以使您的 div 静态显示在窗口顶部:

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

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

<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>

关于javascript - 有没有办法在我的网站上制作一个向下滚动时位于顶部的 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10464287/

相关文章:

javascript - 为什么这些数据没有发送到 Redux 中?

html - 在 wordpress 中添加了不需要的左填充

html - 在图像上设置叠加图像

css - (x)html/css : list items distributed in columns

xhtml - 在 xhtml 页面中使用 schema.org 标记和评论时,不显示星级和聚合评分

html - 三部分动态间距 wo/Table 和绝对定位

javascript - 如何在 PHP 中将动态文本附加到 url 中?

javascript - 添加类时 Firefox 转换

javascript - iron-ajax 尝试通过 xhr 多行字符串或数组子表达式传输

css - Angular Material 建议使用 Visual Studio 社区版 2015 的 md- 标签