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

半城伤御伤魂 提交于 2020-01-01 07:20:45

问题


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.

I need this exact same behaviour that 9gag offers -> http://9gag.com/gag/293756

Thanks!


回答1:


Do the following:

  1. Create a scroll event handler on the $(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.
  3. If yes, set the element to position: fixed with top: 0. You may also need to adjust the left attribute, depending on your layout.
  4. If no, set the element to position: static.



回答2:


Use the Jquery Waypoints plugin: http://imakewebthings.github.com/jquery-waypoints/

Extremely easy to implement.




回答3:


The code that creates exactly the same behavior as 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 -->


来源:https://stackoverflow.com/questions/7591107/how-to-create-a-bar-that-stays-on-top-when-scrolling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!