许多网站都有这样一个功能,当你滚动页面时,某个元素会固定在页面上直到你滚到侧栏底部等特定位置,然后它就会锚定在该侧栏底部。当你向上滚动时,它开始像一个固定的元素一样,随着你的滚动保持在屏幕上。这个功能被称为什么,如何实现?
代码的根源是jQuery的.scroll()
处理函数,因此这是一个很好的起点。据我所知,这种效果没有官方名称,但我在许多地方看到了它的描述,现在有人想知道它,我却找不到它!
编辑这就是我在寻找的内容:CSS-Tricks上的Persistent Headers
Chris Coyier技术的基础是html:
<article class="persist-area">
<h1 class="persist-header">
<!-- stuff and stuff -->
</article>
CSS:
.floatingHeader {
position: fixed;
top: 0;
visibility: hidden;
}
以及jQuery:
function UpdateTableHeaders() {
$(".persist-area").each(function() {
var el = $(this),
offset = el.offset(),
scrollTop = $(window).scrollTop(),
floatingHeader = $(".floatingHeader", this)
if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
floatingHeader.css({
"visibility": "visible"
});
} else {
floatingHeader.css({
"visibility": "hidden"
});
};
});
}
// DOM Ready
$(function() {
var clonedHeaderRow;
$(".persist-area").each(function() {
clonedHeaderRow = $(".persist-header", this);
clonedHeaderRow
.before(clonedHeaderRow.clone())
.css("width", clonedHeaderRow.width())
.addClass("floatingHeader");
});
$(window)
.scroll(UpdateTableHeaders)
.trigger("scroll");
});
var $header = $("#header");
var HeaderOffset = $header.position().top;
$("#headerContainer").css({ height: $header.height() });
$("#container").scroll(function() {
if($(this).scrollTop() > HeaderOffset) {
$header.addClass("fixedTop");
} else {
$header.removeClass("fixedTop");
}
});
CSS:
#containerParent {
position: relative;
width: 180px;
}
#container {
height:200px;
overflow:auto;
}
#header {
background:black;
color:white;
width: 100%;
}
.fixedTop {
position: absolute;
top: 0;
}
示例HTML:
<h1>Fixed Position Header - after a point</h1>
<div id="containerParent">
<div id="container">
This text is an example of content that might occur before the header.
<div id="headerContainer">
<div id="header">Header</div>
</div>
<div>
Below is enough content to trigger scrolling.
line 1 <br/>
line 2 <br/>
line 3 <br/>
line 4 <br/>
line 5 <br/>
line 6 <br/>
line 7 <br/>
line 8 <br/>
line 9 <br/>
line 10 <br/>
line 11 <br/>
line 12 <br/>
line 13 <br/>
line 14 <br/>
line 15 <br/>
</div>
</div>
</div>