Position fixed when scrolled passed certain amount of pixels

匿名 (未验证) 提交于 2019-12-03 02:53:02

问题:

I'm looking for a way to position the #header element of my page as "Fixed" only after having scrolled downward for about 170 pixels.

Above the header is a banner, so when people scroll down, I would like the banner to scroll away, the header to stay fixed when it hits the top of the window, and the page content to scroll underneath the header.

http://jsfiddle.net/tdskate/zEDMv/

回答1:

This is the general idea although you may want to fudge around with the css a bit.

var header = $("#header"); $(document).scroll(function(e) {     if($(this).scrollTop() > $("#banner").height()) {         header.css({"position" : "fixed", "top" : "0"});     } else {         header.css("position", "relative");     } }); 


回答2:

You need to check for the different scroll positions:

var $header = $('#header'),     headerPos = $header.position().top,     $win = $(window);  $win.scroll(function() {      if ( $win.scrollTop() >= headerPos) {          $header.css({             'position':'fixed',             'top':0,             'width': '100%'         });      }      if ( $win.scrollTop() <= headerPos ) {          $header.css({             'position': 'static'         });      }  }); 

http://jsfiddle.net/DOSBeats/zEDMv/10/



回答3:

Here's a slightly more concise version:

var header = $('#header'),     bannerHeight = $('#banner').height(),     win = $(window);  win.scroll(function() {     header.css({ top: Math.max(Number(win.scrollTop() - bannerHeight), 0) }); }); 


回答4:

Here is a demo of a jquery plugin that takes care of this. Similar to John's answer above, but the plugin takes the solution a bit farther.

Demo: http://jsfiddle.net/ZczEt/

Plugin and source: https://github.com/bigspotteddog/ScrollToFixed

Usage:

$(document).ready(function() {     $('.header').scrollToFixed(); }); 


回答5:

I think this should work: http://jsfiddle.net/Skooljester/K2mFT/. However, you'll need to define a width on your header or else it'll shrink when it becomes fixed.



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