我想为此滚动做粘性标题,因此我编写了以下代码
var body = document.body;
var scrollUp = "scroll-up";
var scrollDown = "scroll-down";
var lastScroll = 0;
if (window.addEventListener) {
window.addEventListener("scroll", scrollHandler);
} else {
window.attachEvent("scroll", scrollHandler);
}
function scrollHandler() {
var currentScroll = window.pageYOffset;
if (currentScroll === 0) {
body.classList.remove(scrollDown);
body.classList.remove(scrollUp);
return;
}
if (currentScroll > lastScroll && !body.classList.contains(scrollDown)) {
// down
body.classList.remove(scrollUp);
body.classList.add(scrollDown);
} else if (currentScroll < lastScroll && body.classList.contains(scrollDown)) {
// up
body.classList.remove(scrollDown);
body.classList.add(scrollUp);
}
lastScroll = currentScroll;
}
Sticky标头正在工作,但在某些分辨率下也闪烁,有时也卡住了。请帮助我。谢谢
您只需要选择nav元素而不是body检查摘要,仅在向上滚动时导航栏将被固定
var nav = document.getElementsByTagName('nav')[0];
var scrollUp = "scroll-up";
var scrollDown = "scroll-down";
var lastScroll = 0;
if (window.addEventListener) {
window.addEventListener("scroll", scrollHandler);
} else {
window.attachEvent("scroll", scrollHandler);
}
function scrollHandler() {
var currentScroll = window.pageYOffset;
if (currentScroll === 0) {
nav.classList.remove(scrollDown);
nav.classList.remove(scrollUp);
return;
}
if (currentScroll > lastScroll && !nav.classList.contains(scrollDown)) {
// down
nav.classList.remove(scrollUp);
nav.classList.add(scrollDown);
} else if (currentScroll < lastScroll && nav.classList.contains(scrollDown)) {
// up
nav.classList.remove(scrollDown);
nav.classList.add(scrollUp);
}
lastScroll = currentScroll;
}
body {
padding: 0;
margin: 0;
width: 100%;
height: 2000px;
}
nav {
width: 100%;
height: 50px;
background: royalblue;
}
.scroll-down {
position: static;
top: initial;
left: initial;
}
.scroll-up {
position: fixed;
top: 0;
left: 0;
}
<nav class="scroll-up"></nav>