[英]Make div stick to top of page after scrolling past another div?
<div id="header"></div>
<div id="sticky"></div>
<div id="section"></div>
<div id="footer"></div>
<style>
body { margin: 0px; background-color: #e3e3e3; }
#header { background-color: #cb5454; height: 140px; }
#sticky { background-color: #546bcb; height: 70px; }
#section { height: 1500px; }
#footer { background-color: #cb5454; height: 140px; }
</style>
這是我的代碼: http : //jsfiddle.net/uaqh018d/
我希望 #sticky 在滾動過 #header 后粘在頁面頂部。 我也希望它隱藏直到卡住。 然后當然在滾動回#header 后再次取消粘貼+隱藏。
我怎樣才能做到這一點?
我建議在#sticky
准備好固定到屏幕頂部時向它添加一個類,然后在您想“取消粘貼”它時刪除該類。 然后您可以在 CSS 中操作該類。
例如,對於已fixed
的類,您可以在 CSS 中添加以下內容:
#sticky {
display: none;
background-color: #546bcb;
height: 70px;
}
#sticky.fixed {
display: block;
position: fixed;
top: 0;
width: 100%;
}
然后你的jQuery看起來像這樣:
$(window).scroll(function() {
var distanceFromTop = $(this).scrollTop();
if (distanceFromTop >= $('#header').height()) {
$('#sticky').addClass('fixed');
} else {
$('#sticky').removeClass('fixed');
}
});
這是更新的FIDDLE
我可能還會推薦一些 jQuery 淡入淡出或幻燈片效果(請參閱小提琴)。
您可以使用position: fixed
並在 js 中檢測用戶何時滾動,如下所示:
$(document).scroll(function() { //detect when user scroll to top and set position to relative else sets position to fixed $("#sticky").css({ "top": "0", "position": $(this).scrollTop() > 140 ? "fixed" : "relative" }); });
body { margin: 0px; background-color: #e3e3e3; } #header { background-color: #cb5454; height: 140px; } #sticky { background-color: #546bcb; height: 70px; width: 100%; position: fixed; } #section { height: 1500px; } #footer { background-color: #cb5454; height: 140px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="header"></div> <div id="sticky"></div> <div id="section"></div> <div id="footer"></div>
參考
就我而言,我想要粘貼的 div 位於另一個 div 內(即沒有粘在頁面上,而是在頁面一側的另一個固定 div 中)。 這是我對@bowhart 的答案的改編,以解決給定 React 組件(sticky_adapter.js)的這個問題:
module.exports.makeItSticky = function(thisReactComponent, parentScrollNode = window) {
const thisNode = $(ReactDOM.findDOMNode(thisReactComponent));
const position = thisNode.position();
// Uncomment for verbose logging
//console.log("Initial position: " + UIUtils.stringify(position));
const scrollContainer = $(parentScrollNode);
scrollContainer.scroll(() => {
const distanceFromTop = scrollContainer.scrollTop();
// Uncomment for verbose logging
//console.log("ScrollTop: " + distanceFromTop);
if (distanceFromTop > position.top) {
thisNode.addClass("stick-to-top");
} else {
thisNode.removeClass("stick-to-top");
}
});
};
現在,為了使任何 React 組件具有粘性,我只需添加到類中:
componentDidMount() {
StickyAdapter.makeItSticky(this, ".some-other-div-which-is-the-container");
}
最后,粘性類的 css:
.stick-to-top {
display: block;
position: sticky;
top: 0;
z-index: 10;
}
嘿,這是一個老問題,但對於新訪問者,我認為您只需要將此 css 代碼添加到#sticky:
#sticky { position:sticky;top:0; }
並且不需要 javascript。
粘性在相對和固定之間切換,具體取決於滾動位置。
並且不要忘記,父級也不應該有溢出屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.