可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.