简体   繁体   English

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

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

I'm trying to create a div that stays fixed on top when a user scrolls down and when he scrolls back up, goes back to the original position. 我正在尝试创建一个div,当用户向下滚动时,它保持固定在顶部;当他向上滚动时,返回到原始位置。

I need this exact same behaviour that 9gag offers -> http://9gag.com/gag/293756 我需要9gag提供的完全相同的行为-> http://9gag.com/gag/293756

Thanks! 谢谢!

Do the following: 请执行下列操作:

  1. Create a scroll event handler on the $(window) . $(window)上创建一个滚动事件处理程序
  2. In this event handler, check if the user has scrolled lower than the top of the element you always want in view. 在此事件处理程序中,检查用户滚动到的位置是否低于您始终希望在视图中滚动的元素的顶部。 You can use offest and scrollTop methods to do this. 您可以使用offestscrollTop方法来执行此操作。
  3. If yes, set the element to position: fixed with top: 0 . 如果是,请将元素设置为position: fixedtop: 0 position: fixed You may also need to adjust the left attribute, depending on your layout. 根据您的布局,您可能还需要调整left属性。
  4. If no, set the element to position: static . 如果否,则将元素设置为position: static

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

Extremely easy to implement. 极其容易实现。

The code that creates exactly the same behavior as 9gag.com: 创建行为与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