What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

后端 未结 6 559
醉梦人生
醉梦人生 2020-11-28 20:39

I\'m relatively new to jQuery, but so far what I\'ve seen I like. What I want is for a div (or any element) to be across the top of the page as if \"position: fixed\" worked

6条回答
  •  北海茫月
    2020-11-28 21:10

    HTML/CSS Approach

    If you are looking for an option that does not require much JavaScript (and and all the problems that come with it, such as rapid scroll event calls), it is possible to gain the same behavior by adding a wrapper

    and a couple of styles. I noticed much smoother scrolling (no elements lagging behind) when I used the following approach:

    JS Fiddle

    HTML

    [Fixed Content]
    [Scrolling Content]

    CSS

    #wrapper { position: relative; }
    #fixed { position: fixed; top: 0; right: 0; }
    #scroller { height: 100px; overflow: auto; }
    

    JS

    //Compensate for the scrollbar (otherwise #fixed will be positioned over it).
    $(function() {
      //Determine the difference in widths between
      //the wrapper and the scroller. This value is
      //the width of the scroll bar (if any).
      var offset = $('#wrapper').width() - $('#scroller').get(0).clientWidth;
    
      //Set the right offset
      $('#fixed').css('right', offset + 'px');​
    });
    

    Of course, this approach could be modified for scrolling regions that gain/lose content during runtime (which would result in addition/removal of scrollbars).

提交回复
热议问题