[英]how to set the position of element to fixed on scroll to certain height and make it normal when not that height?
[英]How to make an element fake position:fixed so it acts fixed until a certain scroll height, then attaches?
許多網站都有一個功能,當你滾動到某個點(如側欄的末端)時,頁面上會出現一個固定在頁面上的元素,然后它會錨定到該側邊欄的底部。 向上滾動后,它開始像固定元素一樣,在滾動時保留在屏幕上。
你怎么稱呼這個怎么做?
您可以將位置設置為絕對和附加的滾動事件到頁面,並且在那種情況下您可以根據滾動條的位置更改頂部css值(在jQuery中它是純javascript中的scrollTop它應該類似),然后添加頂部更改的條件只有當scrollTop小於特定值,如offset.top +側邊欄的高度。
你可以使用https://github.com/wduffy/jScroll,但我知道這不是你想要的,滾動和div進入視圖之間有一個延遲,它總是不得不追趕。
代碼的根是jQuery的.scroll()
處理程序 ,所以這是一個很好的起點。 據我所知,這個效果沒有官方名稱,但我看到它描述了很多地方,現在有人想知道它,我不能發現它!
編輯這是我在尋找的東西: CSS-Tricks上的持久標題
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");
});
收聽滾動事件,當它們滾動瀏覽要保留在視圖中的元素時,您將其位置更改為“固定”。
我創建了一個jsFiddle來說明這個: http : //jsfiddle.net/luisperezphd/EcsS6/
有幾點要記住,例如固定元素將相對於窗口或第一個父元素放置position: relative
。
其次,當你將一個元素更改為fixed
它會折疊它曾經存在的空間,導致它下面的內容向上移動。 如果你想讓效果看起來很流暢,你必須在它的位置放置一些占用相同空間的東西。
在我的jsFiddle示例中,我通過將header元素包裝在另一個元素中然后將其高度設置為匹配(以編程方式)來完成此操作。 雖然有幾種不同的方法可以實現這一目標。
我還將包含下面的代碼,在我的例子中我使用jQuery。
JavaScript的:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.