我是 jquery 的新手,希望在我向下滚动浏览器中的特定位置后使 div 向上滚动并固定在顶部,就像 http://www.airbnb.com/jobs/ 一样。
最佳答案
尝试以下 DEMO
这与我的其他答案 (Answer) 相同,只是更改了一些值。原生 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:
<div class="container">
<div id="header" class="header">
Hello World
</div>
</div>
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;
}
希望对你有帮助
关于jquery - 如何使div向上滚动并固定在顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11627636/