gpt4 book ai didi

javascript - 当用户滚动时,粘性导航栏重新出现

转载 作者:行者123 更新时间:2023-12-04 13:30:30 24 4
gpt4 key购买 nike

我正在尝试创建一些功能,如果用户向下滚动,sitcky 导航栏标题将消失。如果用户向上滚动,它将重新出现。
我几乎明白了,唯一的问题是当我滚动时,标题消失,只有在我停止滚动时才会重新出现。实际上它在重新出现之前有点闪烁。
这就是我想要实现的目标:
https://www.w3schools.com/howto/howto_js_navbar_hide_scroll.asp
HTML:

<header id="site-header" class="header-footer-group sticky-element-original element-is-sticky" role="banner" style="margin-top: 0px !important; margin-left: 0px !important; position: fixed; left: 0px; top: 0px; width: 651px; padding: 0px; z-index: 99999;">

...

</header>
Javascript:
<script>
/* When the user scrolls down, hide the navbar. When the user scrolls up, show the navbar */
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("site-header").style.top = "0";
} else {
document.getElementById("site-header").style.top = "-100%";
}
prevScrollpos = currentScrollPos;
}
</script>

最佳答案

滚动事件是一把机枪......它在一次鼠标滚轮旋转时会发射 10 次以上。
尝试缓冲一下这些事件...结合 clearTimeout/setTimeout :

/* When the user scrolls down, hide the navbar. When the user scrolls up, show the navbar */

let scrollTimeout

var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("site-header").style.top = "0";
} else {
document.getElementById("site-header").style.top = "-100%";
}

// Event buffering here
clearTimeout(scrollTimeout)
scrollTimeout = setTimeout(function(){
prevScrollpos = currentScrollPos;
},500) // This delay may need adjustment...
}
#site-header{
background: yellow;
}

#page{
height: 50000px;
background: blue;
}
<header id="site-header" class="header-footer-group sticky-element-original element-is-sticky" role="banner" style="margin-top: 0px !important; margin-left: 0px !important; position: fixed; left: 0px; top: 0px; width: 651px; padding: 0px; z-index: 99999;">

I'm the header... I know I'm ugly, but that is just a demo.

</header>

<div id="page"></div>

关于javascript - 当用户滚动时,粘性导航栏重新出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65386100/

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