理解 "hide nav-bar on scroll" 代码 - Javascript
Understanding "hide nav-bar on scroll" code - Javascript
我正在学习 JS,我有一个测试页面,我可以在其中练习我的新“发现”。
我遵循了 Youtube (Here the link if somebody's interested) 上关于如何 hide/show 基于滚动事件的导航栏的教程。我将它应用于我的测试页面,当然它运行良好,正如您从代码片段中看到的那样,但我在理解 2 个特定点时遇到了一些问题。希望有人能用“可怜”的话来解释他们。
所以,这里是 滚动事件的 JS 代码
const header = document.querySelector('header');
let prev = window.pageYOffset;
window.addEventListener('scroll', function(){
let current = window.pageYOffset;
if(prev < current){
header.classList.add('hide');
}
else {
header.classList.remove('hide');
}
prev = current;
})
点 n°1
- 在 IF 语句 中,如果没有赋值,
let prev;
如何知道它小于 let current;
?我试着想像“当我向上滚动时,向上滚动的视口部分小于当前显示的屏幕部分。”。这种“理论”是有效的,但只有在向上滚动的内容部分大于显示的实际内容部分时才会有效。一旦到了这个地步,我的“理论”就没有意义了。
点 n°2
- 为什么需要最后一条语句:
prev = current;
?我注意到 如果我不写 最后一条语句,当我向上滚动时导航栏将 隐藏 ,但当我向下滚动时它会不再显示。
片段
const burger = document.querySelector('.burger');
const nav = document.querySelector('nav');
burger.addEventListener('click', () => {
nav.classList.toggle('active');
burger.classList.toggle('hide');
xicon.classList.toggle('active');
});
const xicon = document.querySelector('.xicon');
xicon.addEventListener('click', function() {
nav.classList.toggle('active');
xicon.classList.toggle('active');
burger.classList.toggle('hide');
})
const header = document.querySelector('header');
let prev = window.pageYOffset;
window.addEventListener('scroll', function(){
let current = window.pageYOffset;
if(prev < current){
header.classList.add('hide');
}
else {
header.classList.remove('hide');
}
prev = current;
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.logoandicon {
display: flex;
justify-content: space-between;
align-items: center;
background: powderblue;
padding: .7em 0;
}
.logo {
margin-left: .5em;
}
.burger {
margin-right: 1em;
z-index: 2;
}
.burger.hide {
display: none;
}
nav ul li a {
text-decoration: none;
color: black;
font-family: verdana;
}
nav ul li {
text-align: center;
list-style: none;
}
nav {
padding: 1em 0;
line-height: 2em;
background: lightgreen;
display: none;
}
nav.active {
display: block;
}
.xicon {
position: absolute;
right: 1em;
display: none;
}
.xicon.active {
display: block;
}
header {
width: 100vw;
position: fixed;
}
header.hide {
display: none;
}
main {
padding-top: 4em;
}
<header>
<div class="logoandicon">
<h1 class="logo">Logo</h1>
<img src="menu.svg" class="burger" width="30px" alt="burger-icon">
<img src="xicon.svg" class="xicon" width="27px" alt="x-icon">
</div>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Contacts</a></li>
</ul>
</nav>
</header>
<main>
<h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro ut, animi iure sequi voluptatem maiores, aspernatur tempora, ipsa tempore, voluptate sint. Maiores quos inventore cumque reiciendis iusto illum, aut quam, suscipit temporibus veniam. Reprehenderit distinctio velit eveniet blanditiis, animi optio voluptas dolores repellendus ad itaque veritatis. Expedita deserunt, ab dolor accusamus sequi eum optio. Fuga dolorum, quod qui laboriosam iure molestiae magnam explicabo! Accusamus, alias, non. Eius voluptas in aspernatur natus illo et possimus optio, cupiditate saepe quisquam totam laboriosam ullam nihil consequatur rem earum ratione perspiciatis. Quo impedit ipsum assumenda suscipit unde inventore dolores quas? Ipsa aliquam sapiente rerum sit autem magni ad dolore iste vero optio saepe, impedit eveniet suscipit, deserunt. Modi architecto laudantium placeat beatae repellat harum deleniti facere deserunt officia unde mollitia error praesentium, sunt fugit recusandae soluta facilis earum voluptatem libero consectetur illum debitis quos! Odit unde, quo non blanditiis vitae aperiam obcaecati provident praesentium quas qui, veritatis enim accusamus iusto rerum harum porro maxime sit amet cum odio suscipit ipsum nulla adipisci. Totam consectetur quas ipsa. Natus officiis, eveniet reprehenderit neque rem sint eum, ratione, numquam blanditiis nisi culpa repudiandae nemo beatae. Ea cum officiis vel, sed distinctio, voluptatibus quibusdam! Soluta voluptate, atur tempora, ipsa tempore, voluptate sint. Maiores quos inventore cumque reiciendis iusto illum, aut quam, suscipit temporibus veniam. Reprehenderit distinctio velit eveniet blanditiis, animi optio voluptas dolores repellendus ad itaque veritatis. Expedita deserunt, ab dolor accusamus sequi eum optio. Fuga dolorum, quod qui laboriosam iure molestiae magnam explicabo! Accusamus, alias, non. Eius voluptas in aspernatur natus illo et possimus optio, cupiditate saepe quisquam totam laboriosam ullam nihil consequatur rem earum ratione perspiciatis. Quo impedit ipsum assumenda suscipit unde inventore dolores quas? Ipsa aliquam sapiente rerum sit autem magni ad dolore iste vero optio saepe, impedit eveniet suscipit, deserunt. Modi architecto laudantium placeat beatae repellat harum deleniti facere deserunt officia unde mollitia error praesentium, sunt fugit recusandae soluta facilis earum voluptatem libero consectetur illum debitis quos! Odit unde, quo non blanditiis vitae aperiam obcaecati provident praesentium quas qui, veritatis enim accusamus iusto rerum harum porro maxime sit amet cum odio suscipit ipsum nulla adipisci. Totam consectetur quas ipsa. Natus officiis, eveniet reprehenderit neque rem sint eum, ratione, numquam blanditiis nisi culpa repudiandae nemo beatae. Ea cum officiis vel, sed distinctio, voluptatibus quibusdam! Soluta voluptate, non facilis?</h1>
</main>
<script src="main.js">
</script>
我会尽力解释,然后提供注释掉的代码。
它不完全是视口的高度,window.pageYOffset 计算您从 window 顶部向下滚动的距离。当您加载页面时,该数字为 0。我建议查看 MDN Docs
然后当您滚动时,您当前的偏移量设置为 prev,而您的新偏移量设置为当前。您可以尝试 console.log(current, prev)
并查看它在您上下滚动时如何变化。当 prev 和 current 都有值时,它们被比较,如果 current > prev
,它显示元素。
prev = current
负责保存您之前的偏移量,因此有一些东西可以与您的新当前值进行比较。
const header = document.querySelector("header");
let prev = window.pageYOffset; // 0 when page loads, otherwise stores previous 'current' value
window.addEventListener("scroll", function () {
let current = window.pageYOffset; // your current offset from the top of the document
// Add console.log(current, prev) here if you want to see how the offset changes, you'll notice that prev value is always smaller when you scroll down and bigger when you scroll up
if (prev < current) {
header.classList.add("hide");
} else {
header.classList.remove("hide");
}
prev = current; // Set current variable to prev variable so there's something to compare
});
Point n°1 - 当页面加载时,pageYOffset
值被分配给 prev
变量并激活滚动事件侦听器。因此,当您滚动时,当前 pageYOffset
值被分配给 current
变量,然后将其与 prev
变量进行比较。因此,正如条件所说,如果 prev
值小于 current
则隐藏导航栏,否则显示导航栏。
示例 - 当页面加载时,prev
的值将被分配为 0。当您滚动时,它将大于 0。
要点 n°2 - 每次滚动时,事件都会 运行 函数。因此,当您向下滚动时,current
值将每隔 time.So 使用 prev = current
更新一次,您将 current
值存储到 prev
值。这让用户在 he/she 向上滚动后获得滚动条。
示例 - 用户向下滚动,current
的值存储到 prev
。假设它为 current = 220
并存储在 prev
中。因此,当用户向上滚动时,current
值将为 215。因此 prev
将大于 current
并显示导航栏。
你需要理解What is window.pageYOffset
and how is work before explain your code.If you want to more customize other event in javascript, you must learn window
and addEventListener。当你学习后,你会清楚这些代码的工作原理,你可以在 javascript 中用滚动做很多事情。
你可以在javascript.And中使用console.log(SomeThing)
进行调试,然后你可以逐步检查。示例:
const header = document.querySelector('header');
let prev = window.pageYOffset;
console.log("Start State for prev:" + prev); //debug for initial point
window.addEventListener('scroll', function(){
let current = window.pageYOffset;
console.log("Current State for current:" + current); //debug for current point when you scroll
// you will see which condition is happen now
// when you start scroll down "prev" is always smaller than "current".So condition is true, header will hide.
// when you scroll up "prev" is always smaller than "current".So condition is true, header will hide.
if(prev < current){
header.classList.add('hide');
}
else {
header.classList.remove('hide');
}
//But you want to show scroll up, you need to put current to prev.
prev = current;
})
window.pageYOffset
return 某些点从 0 开始。当你向下滚动时,window.pageYOffset
return 点是 increase.When 你向上滚动 window.pageYOffset
return 点是 decrese.Because 如果不在滚动事件中使用,则使用 window.addEventListener
进行滚动。 window.pageYOffset
return 点不会 change.Therefore, prev
值会固定,因为它有调用一次。 current
使用时值会发生变化 scroll.When 你明白上面的代码有效,你可以检查以下答案以获得你的观点。
点 n°1
第一次,你调用这些 javascript,prev
得到一些 value.let 说 prev
得到 '0'。这将是固定的。 current
得到一些与 prev
相同的值。所以,条件是假的。 header
不会躲。向下滚动时,current
值增加。 prev
值相同。所以,条件为真。 header
将 hide.When 您向上滚动 current
值减少。 prev
值为same.When current
改为'0' value.Condition为假,header
不会隐藏。
第 2 点
您想在向上滚动时取消隐藏。您需要将 prev
值设置为高于 current
。向上滚动是减少。让current
为'10',prev
赋值为'10'。下一次,current
将减少'9'。 prev
是'10'。条件为假。header
不会hide.Therefore,你需要将current
赋值给prev
。
我正在学习 JS,我有一个测试页面,我可以在其中练习我的新“发现”。
我遵循了 Youtube (Here the link if somebody's interested) 上关于如何 hide/show 基于滚动事件的导航栏的教程。我将它应用于我的测试页面,当然它运行良好,正如您从代码片段中看到的那样,但我在理解 2 个特定点时遇到了一些问题。希望有人能用“可怜”的话来解释他们。
所以,这里是 滚动事件的 JS 代码
const header = document.querySelector('header');
let prev = window.pageYOffset;
window.addEventListener('scroll', function(){
let current = window.pageYOffset;
if(prev < current){
header.classList.add('hide');
}
else {
header.classList.remove('hide');
}
prev = current;
})
点 n°1
- 在 IF 语句 中,如果没有赋值,
let prev;
如何知道它小于let current;
?我试着想像“当我向上滚动时,向上滚动的视口部分小于当前显示的屏幕部分。”。这种“理论”是有效的,但只有在向上滚动的内容部分大于显示的实际内容部分时才会有效。一旦到了这个地步,我的“理论”就没有意义了。
点 n°2
- 为什么需要最后一条语句:
prev = current;
?我注意到 如果我不写 最后一条语句,当我向上滚动时导航栏将 隐藏 ,但当我向下滚动时它会不再显示。
片段
const burger = document.querySelector('.burger');
const nav = document.querySelector('nav');
burger.addEventListener('click', () => {
nav.classList.toggle('active');
burger.classList.toggle('hide');
xicon.classList.toggle('active');
});
const xicon = document.querySelector('.xicon');
xicon.addEventListener('click', function() {
nav.classList.toggle('active');
xicon.classList.toggle('active');
burger.classList.toggle('hide');
})
const header = document.querySelector('header');
let prev = window.pageYOffset;
window.addEventListener('scroll', function(){
let current = window.pageYOffset;
if(prev < current){
header.classList.add('hide');
}
else {
header.classList.remove('hide');
}
prev = current;
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.logoandicon {
display: flex;
justify-content: space-between;
align-items: center;
background: powderblue;
padding: .7em 0;
}
.logo {
margin-left: .5em;
}
.burger {
margin-right: 1em;
z-index: 2;
}
.burger.hide {
display: none;
}
nav ul li a {
text-decoration: none;
color: black;
font-family: verdana;
}
nav ul li {
text-align: center;
list-style: none;
}
nav {
padding: 1em 0;
line-height: 2em;
background: lightgreen;
display: none;
}
nav.active {
display: block;
}
.xicon {
position: absolute;
right: 1em;
display: none;
}
.xicon.active {
display: block;
}
header {
width: 100vw;
position: fixed;
}
header.hide {
display: none;
}
main {
padding-top: 4em;
}
<header>
<div class="logoandicon">
<h1 class="logo">Logo</h1>
<img src="menu.svg" class="burger" width="30px" alt="burger-icon">
<img src="xicon.svg" class="xicon" width="27px" alt="x-icon">
</div>
<nav>
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Contacts</a></li>
</ul>
</nav>
</header>
<main>
<h1>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro ut, animi iure sequi voluptatem maiores, aspernatur tempora, ipsa tempore, voluptate sint. Maiores quos inventore cumque reiciendis iusto illum, aut quam, suscipit temporibus veniam. Reprehenderit distinctio velit eveniet blanditiis, animi optio voluptas dolores repellendus ad itaque veritatis. Expedita deserunt, ab dolor accusamus sequi eum optio. Fuga dolorum, quod qui laboriosam iure molestiae magnam explicabo! Accusamus, alias, non. Eius voluptas in aspernatur natus illo et possimus optio, cupiditate saepe quisquam totam laboriosam ullam nihil consequatur rem earum ratione perspiciatis. Quo impedit ipsum assumenda suscipit unde inventore dolores quas? Ipsa aliquam sapiente rerum sit autem magni ad dolore iste vero optio saepe, impedit eveniet suscipit, deserunt. Modi architecto laudantium placeat beatae repellat harum deleniti facere deserunt officia unde mollitia error praesentium, sunt fugit recusandae soluta facilis earum voluptatem libero consectetur illum debitis quos! Odit unde, quo non blanditiis vitae aperiam obcaecati provident praesentium quas qui, veritatis enim accusamus iusto rerum harum porro maxime sit amet cum odio suscipit ipsum nulla adipisci. Totam consectetur quas ipsa. Natus officiis, eveniet reprehenderit neque rem sint eum, ratione, numquam blanditiis nisi culpa repudiandae nemo beatae. Ea cum officiis vel, sed distinctio, voluptatibus quibusdam! Soluta voluptate, atur tempora, ipsa tempore, voluptate sint. Maiores quos inventore cumque reiciendis iusto illum, aut quam, suscipit temporibus veniam. Reprehenderit distinctio velit eveniet blanditiis, animi optio voluptas dolores repellendus ad itaque veritatis. Expedita deserunt, ab dolor accusamus sequi eum optio. Fuga dolorum, quod qui laboriosam iure molestiae magnam explicabo! Accusamus, alias, non. Eius voluptas in aspernatur natus illo et possimus optio, cupiditate saepe quisquam totam laboriosam ullam nihil consequatur rem earum ratione perspiciatis. Quo impedit ipsum assumenda suscipit unde inventore dolores quas? Ipsa aliquam sapiente rerum sit autem magni ad dolore iste vero optio saepe, impedit eveniet suscipit, deserunt. Modi architecto laudantium placeat beatae repellat harum deleniti facere deserunt officia unde mollitia error praesentium, sunt fugit recusandae soluta facilis earum voluptatem libero consectetur illum debitis quos! Odit unde, quo non blanditiis vitae aperiam obcaecati provident praesentium quas qui, veritatis enim accusamus iusto rerum harum porro maxime sit amet cum odio suscipit ipsum nulla adipisci. Totam consectetur quas ipsa. Natus officiis, eveniet reprehenderit neque rem sint eum, ratione, numquam blanditiis nisi culpa repudiandae nemo beatae. Ea cum officiis vel, sed distinctio, voluptatibus quibusdam! Soluta voluptate, non facilis?</h1>
</main>
<script src="main.js">
</script>
我会尽力解释,然后提供注释掉的代码。
它不完全是视口的高度,window.pageYOffset 计算您从 window 顶部向下滚动的距离。当您加载页面时,该数字为 0。我建议查看 MDN Docs
然后当您滚动时,您当前的偏移量设置为 prev,而您的新偏移量设置为当前。您可以尝试 console.log(current, prev)
并查看它在您上下滚动时如何变化。当 prev 和 current 都有值时,它们被比较,如果 current > prev
,它显示元素。
prev = current
负责保存您之前的偏移量,因此有一些东西可以与您的新当前值进行比较。
const header = document.querySelector("header");
let prev = window.pageYOffset; // 0 when page loads, otherwise stores previous 'current' value
window.addEventListener("scroll", function () {
let current = window.pageYOffset; // your current offset from the top of the document
// Add console.log(current, prev) here if you want to see how the offset changes, you'll notice that prev value is always smaller when you scroll down and bigger when you scroll up
if (prev < current) {
header.classList.add("hide");
} else {
header.classList.remove("hide");
}
prev = current; // Set current variable to prev variable so there's something to compare
});
Point n°1 - 当页面加载时,pageYOffset
值被分配给 prev
变量并激活滚动事件侦听器。因此,当您滚动时,当前 pageYOffset
值被分配给 current
变量,然后将其与 prev
变量进行比较。因此,正如条件所说,如果 prev
值小于 current
则隐藏导航栏,否则显示导航栏。
示例 - 当页面加载时,prev
的值将被分配为 0。当您滚动时,它将大于 0。
要点 n°2 - 每次滚动时,事件都会 运行 函数。因此,当您向下滚动时,current
值将每隔 time.So 使用 prev = current
更新一次,您将 current
值存储到 prev
值。这让用户在 he/she 向上滚动后获得滚动条。
示例 - 用户向下滚动,current
的值存储到 prev
。假设它为 current = 220
并存储在 prev
中。因此,当用户向上滚动时,current
值将为 215。因此 prev
将大于 current
并显示导航栏。
你需要理解What is window.pageYOffset
and how is work before explain your code.If you want to more customize other event in javascript, you must learn window
and addEventListener。当你学习后,你会清楚这些代码的工作原理,你可以在 javascript 中用滚动做很多事情。
你可以在javascript.And中使用console.log(SomeThing)
进行调试,然后你可以逐步检查。示例:
const header = document.querySelector('header');
let prev = window.pageYOffset;
console.log("Start State for prev:" + prev); //debug for initial point
window.addEventListener('scroll', function(){
let current = window.pageYOffset;
console.log("Current State for current:" + current); //debug for current point when you scroll
// you will see which condition is happen now
// when you start scroll down "prev" is always smaller than "current".So condition is true, header will hide.
// when you scroll up "prev" is always smaller than "current".So condition is true, header will hide.
if(prev < current){
header.classList.add('hide');
}
else {
header.classList.remove('hide');
}
//But you want to show scroll up, you need to put current to prev.
prev = current;
})
window.pageYOffset
return 某些点从 0 开始。当你向下滚动时,window.pageYOffset
return 点是 increase.When 你向上滚动 window.pageYOffset
return 点是 decrese.Because 如果不在滚动事件中使用,则使用 window.addEventListener
进行滚动。 window.pageYOffset
return 点不会 change.Therefore, prev
值会固定,因为它有调用一次。 current
使用时值会发生变化 scroll.When 你明白上面的代码有效,你可以检查以下答案以获得你的观点。
点 n°1
第一次,你调用这些 javascript,prev
得到一些 value.let 说 prev
得到 '0'。这将是固定的。 current
得到一些与 prev
相同的值。所以,条件是假的。 header
不会躲。向下滚动时,current
值增加。 prev
值相同。所以,条件为真。 header
将 hide.When 您向上滚动 current
值减少。 prev
值为same.When current
改为'0' value.Condition为假,header
不会隐藏。
第 2 点
您想在向上滚动时取消隐藏。您需要将 prev
值设置为高于 current
。向上滚动是减少。让current
为'10',prev
赋值为'10'。下一次,current
将减少'9'。 prev
是'10'。条件为假。header
不会hide.Therefore,你需要将current
赋值给prev
。