如何让div向上滚动并修复到顶部

我是jquery的新手,并希望在浏览器中向下滚动特定位置之后将div向上滚动并修复到顶部,就像http://www.airbnb.com/jobs/

像这样写:

$(window).scroll(function () { var height = $('body').height(); var scrollTop = $(window).scrollTop(); if(scrollTop>500){ $('#header').css({ 'position': 'fixed', 'top' : '0' }); } else{ $('#header').css({ 'position': 'relative', 'top': '500px'}); } }); 

检查这个http://jsfiddle.net/68eXM/14/

尝试以下演示

这与我的其他答案( 答案 )相同,但改变了一些值。 原生JS解决方案。

代码是:

JS:

 window.onscroll=function () { var top = window.pageXOffset ? window.pageXOffset : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop; var head = document.getElementById("header") if(top > 550){ head.style.position = "fixed"; head.style.height="50px" head.style.top="0px" } else { if(head.getAttribute("style")) head.removeAttribute("style") } } 

HTML:

 

CSS:

 .container{ height:2000px; width:100%; background-color:yellow; } .header{ text-align:center; background-color:red; height:100px; position:relative; min-height:50px; width:100%; top:500px; } 

希望能帮助到你

FIDDLE DEMO: http : //jsfiddle.net/collabcoders/PZp8R/3/

扩展它以包含jquery动画,您需要包括jquery,jquery.effects.core.min.js,jquery.effects.slide.min.js和jquery.effects.transfer.min.js文件。

在CSS中,您需要将div的上边距设置为负数,这将是动画的起点。

CSS

 .tophead { width:100%; height: 100px; color:#fff; background-color:#111; } .container { height:2000px; width:100%; margin-top:-100px; } .header{ text-align:center; background-color:#000; height:100px; position:relative; min-height:100px; width:100%; top:500px; color: #fff; }​ 

在你的javascript中,这将动画整个div从-100像素下降到3秒内的0

使用Javascript

 $(document).ready(function () { $(".container").animate({ marginTop: "0" },2000); }); $(window).scroll(function () { var height = $('body').height(); var scrollTop = $(window).scrollTop(); if(scrollTop>500){ $('#header').css({ 'position': 'fixed', 'top' : '0' }); } else { $('#header').css({ 'position': 'relative', 'top': '500px'}); } }); 

HTML

 
Sliding Down Container

它很简单..就像这个例子:

 $(window).scroll(function () { var height = $('body').height(); var scrollTop = $(window).scrollTop(); if(scrollTop>100){ $('#header').css({ 'position': 'fixed', 'top' : '0', 'opacity': '0.7'}); } else { $('#header').css({ 'position': 'relative', 'top': '100px', 'opacity': '1'}); } }); 

http://jsfiddle.net/PZp8R/55/