滚动时如何创建一个保持在顶部的栏?

时间:2011-09-29 00:13:44

标签: javascript html css frontend

我正在尝试创建一个在用户向下滚动时保持固定在顶部的div,当他向上滚动时,返回到原始位置。

我需要与9gag提供的完全相同的行为 - > http://9gag.com/gag/293756

谢谢!

3 个答案:

答案 0 :(得分:4)

执行以下操作:

  1. $(window)上创建scroll event handler
  2. 在此事件处理程序中,检查用户是否已滚动低于您在视图中始终需要的元素的顶部。您可以使用offestscrollTop方法执行此操作。
  3. 如果是,请将元素设置为position: fixed top: 0。您可能还需要调整左侧属性,具体取决于您的布局。
  4. 如果不是,请将元素设置为position: static

答案 1 :(得分:4)

使用Jquery Waypoints插件:http://imakewebthings.github.com/jquery-waypoints/

非常容易实施。

答案 2 :(得分:1)

创建与9gag.com完全相同的行为的代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- tags html, header, body, divs, anything -->

<div id="post-control-bar" class="spread-bar-wrap">
    <div class="spread-bar" style="width:600px">
        Facebook button, Twitter button, anything...
    </div>
</div>

<script type="text/javascript">
window.onscroll = function()
{
    if( window.XMLHttpRequest ) {
        if (document.documentElement.scrollTop > 173 || self.pageYOffset > 173) {
            $('post-control-bar').style.position = 'fixed';
            $('post-control-bar').style.top = '0';
        } else if (document.documentElement.scrollTop < 173 || self.pageYOffset < 173) {
            $('post-control-bar').style.position = 'absolute';
            $('post-control-bar').style.top = '';
        }
    }
}
</script>

<!-- content, footer, anything -->