繁体   English   中英

如何创建滚动时位于顶部的栏?

[英]How to create a bar that stays on top when scrolling?

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

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

谢谢!

请执行下列操作:

  1. $(window)上创建一个滚动事件处理程序
  2. 在此事件处理程序中,检查用户滚动到的位置是否低于您始终希望在视图中滚动的元素的顶部。 您可以使用offestscrollTop方法来执行此操作。
  3. 如果是,请将元素设置为position: fixedtop: 0 position: fixed 根据您的布局,您可能还需要调整left属性。
  4. 如果否,则将元素设置为position: static

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

极其容易实现。

创建行为与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 -->

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM