如果prevScrollPos> currentScrollPos。这怎么可能是真的?当prevScrollPos为0且currentScrollPos从不小于0时
var prevScrollPos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
//Here
if (prevScrollPos > currentScrollPos) {
document.getElementById("navbar").style.top = "0";
} else {
document.getElementById("navbar").style.top = "-50px";
}
prevScrollpos = currentScrollPos;
}
答案 0 :(得分:0)
prevScrollPos
在功能结束时得到更新,因此,当您向上滚动时,currentScrollPos
将小于prevScrollPos
。
此外,您还有错字:
prevScrollPos = currentScrollPos;
答案 1 :(得分:0)
尝试一下
function get_scroll() {
if(window.scrollY > 30)
{
document.getElementById("navbar").style.top = "-50px";
}else{
document.getElementById("navbar").style.top = "0";
}
}
document.getElementsByTagName("BODY")[0].setAttribute("onscroll","get_scroll()");
答案 2 :(得分:0)
我在您的代码中添加了一些注释,这可能会清除您的疑问。
var prevScrollPos = window.pageYOffset;
// here if we assume the prevScrollPos as 0 then when the user scrolls the function gets executed.
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
// Here, say currentScrollPos = 50px; so if condition fails and else block gets executed.
if (prevScrollPos > currentScrollPos) {
document.getElementById("navbar").style.top = "0";
} else {
document.getElementById("navbar").style.top = "-50px";
}
// since the prevScrollpos is being updated here, it will be greater than 0(will be 50px) next time.
prevScrollpos = currentScrollPos;
}
,并且当用户向上滚动时,该函数将再次被调用,这一次,if条件满足,因为50px(prevScrollPos)将大于0(假设他一直向上滚动,则为当前值)。