gpt4 book ai didi

javascript - Sticky Header - buggy 在滚动条上跳跃

转载 作者:可可西里 更新时间:2023-11-01 02:37:56 25 4
gpt4 key购买 nike

我在使用 jQuery 制作粘性 header 时遇到了一个具体问题。我尝试了网络上常用的片段,但我发现到处都是同样的错误。

在特定的文档高度(可滚动直到比调用粘性效果高一点),粘性标题在 position: fixedposition: 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;
}


我还尝试在 #not-sticky 上使用与 #sticky 相同高度的 margin-bottom 来保持恒定的文档高度,但是发生了同样的跳动粘性效果。

有什么办法可以解决这个问题吗?

最佳答案

滚动触发太多次,尝试设置元素 style 总是不可避免地会产生跳跃(甚至几乎不明显,但仍然有锯齿)。

我发现最好的方法是

  1. 克隆我们的元素,
  2. 使该克隆修复
  3. 尝试使用克隆的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>

因此,当您看到“标题”修复 时,这实际上是我们的固定克隆在顶部可见。

关于javascript - Sticky Header - buggy 在滚动条上跳跃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16513794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com