[英]Sticky Header - buggy jumping on scroll
我有一個特定的問題,用jQuery制作一個粘性標頭。 我嘗試了網絡上常用的片段,但我到處都看到了同樣的錯誤。
在特定的文檔高度(可滾動直到調用粘滯效果),粘性標題在position: fixed
和position: static
之間跳轉。
HTML:
<header>
<div id="not-sticky"></div>
<div id="sticky"></div>
</header>
<div id="content"> ...
jQuery的:
var $sticky = $("#sticky");
var offset = $sticky.offset();
var stickyTop = offset.top;
var windowTop = $(window).scrollTop();
$(window).scroll(function() {
windowTop = $(window).scrollTop();
if (windowTop > stickyTop) {
$sticky.css({
position: 'fixed',
top: 0
});
}
else {
$sticky.css({
position: '',
top: ''
});
}
});
CSS:
header {
width: 100%;
}
#not-sticky {
padding: 50px 0;
width: 100%;
}
#sticky {
padding: 24px 0;
position: relative;
width: 100%;
z-index: 25;
}
我還嘗試使用與#sticky
相同高度的#not-sticky
的margin-bottom來保持一個恆定的文檔高度,但是發生了相同的跳躍粘性效果。
有什么想法來解決這個問題嗎?
滾動次數太多次並嘗試設置元素style
將始終不可避免地產生跳躍(甚至幾乎沒有引人注意但仍然是鋸齒狀)。
我找到的最好的方法是
fixed
visibility
風格。 純JS:
;(function(){ /* STICKY */ var sticky = document.getElementById("sticky"), sticky2 = sticky.cloneNode(true); sticky2.style.position = "fixed"; document.body.appendChild(sticky2); function stickIt(){ sticky2.style.visibility = sticky.getBoundingClientRect().top<0 ? "visible" : "hidden"; } stickIt(); window.addEventListener("scroll", stickIt, false ); }());
#sticky{ height:100px; background:#ada; height:50px; position:relative; /* needed for clone: */ top:0; width:100%; } /* Just for this demo: */ *{margin:0;padding:0;} #content{height:2000px; border:3px dashed #444;} h1{padding:40px; background:#888;}
<h1>Logo</h1> <div id="sticky">Sticky header</div> <div id="content">Lorem ipsum...<br>bla bla</div>
因此,當您看到“標題” 修復時 ,實際上我們的固定克隆在頂部可見。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.