javascript 滚动通过一定数量的像素时固定位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7013408/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Position fixed when scrolled passed certain amount of pixels
提问by TD540
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.
我正在寻找一种方法,仅在向下滚动大约 170 像素后,才能将我的页面的 #header 元素定位为“固定”。
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.
标题上方是横幅,所以当人们向下滚动时,我希望横幅滚动离开,标题在到达窗口顶部时保持固定,页面内容滚动到标题下方。
回答by John Kalberer
Thisis the general idea although you may want to fudge around with the css a bit.
这是总体思路,尽管您可能想对 css 稍加修改。
var header = $("#header");
$(document).scroll(function(e) {
if($(this).scrollTop() > $("#banner").height()) {
header.css({"position" : "fixed", "top" : "0"});
} else {
header.css("position", "relative");
}
});
回答by Seth
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'
});
}
});
回答by Lobstrosity
回答by bigspotteddog
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.
这是处理此问题的 jquery 插件的演示。与上面约翰的回答类似,但该插件将解决方案走得更远。
Demo: http://jsfiddle.net/ZczEt/
演示:http: //jsfiddle.net/ZczEt/
Plugin and source: https://github.com/bigspotteddog/ScrollToFixed
插件和源码:https: //github.com/bigspotteddog/ScrollToFixed
Usage:
用法:
$(document).ready(function() {
$('.header').scrollToFixed();
});
回答by ayyp
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.
我认为这应该有效:http: //jsfiddle.net/Skooljester/K2mFT/。但是,您需要在标题上定义一个宽度,否则当它固定时它会缩小。