我创建了一个固定的动画导航栏,它会在滚动时缩小。目前,如果 ypos > 10,它会从 150 缩小到 100。
但是,我想在收缩中添加第二阶段。因此,如果 ypos > 10 但 < 40,它会执行状态 1,如果它大于 40,它会执行状态 2,这将从 100 缩小到 50。
问题:我可以让第一个阶段工作,但我不确定如何观察收缩的第二个状态或如何添加第二个改变第一个的类。
function shrink()
{
ypos = window.pageYOffset;
var topBar = document.getElementById("Top-Bar");
if(ypos > 10 && ypos < 39)
{
topBar.classList.add("shrink");
}
else if(ypos > 40)
{
topBar.classList.add("secondShrink");
}
else
{
topBar.classList.remove("shrink");
topBar.classList.add("secondShrink");
}
};
window.addEventListener("scroll", shrink)
#Top-Bar
{
height: 150px;
width: 100%;
background-color: #ccc;
display: flex;
justify-content: center;
align-items: center;
transition: all .2s ease;
position: fixed;
z-index: 2;
}
#Top-Bar.shrink
{
height: 100px;
transition: all .2s ease;
}
#Top-Bar.shrink.secondShrink
{
height: 50px;
}
.content
{
content: "";
height: 1200px;
position: relative;
z-index: 1;
}
<div id="Top-Bar">
<h1>Site Title</h1>
</div>
<div class="content"></div>
我正在尝试从以下页面重新创建效果:http://www.newmediacampaigns.com/blog/responsive-site-header
最佳答案
正如我在评论中提到的:
On the very first scroll of the page at yPos 0, you add secondShrink to the top bar. At no point do you ever remove it, so from here on out, the top bar will always have .secondShrink. Because of this, normal .shrink will never get hit.
我已经修改了下面的代码,以便一次只有一个缩水贴在顶部栏上。此外,您的 if
和 if else
不考虑 1-10
或 39-40
中的任何内容.很方便,一次鼠标滚轮单击或一次向下箭头单击就是 正好 40 像素。
查看这个清理过的版本:
function shrink()
{
ypos = window.pageYOffset;
var topBar = document.getElementById("Top-Bar");
if(ypos > 0 && ypos <= 40)
{
topBar.classList.remove("secondShrink");
topBar.classList.add("shrink");
}
else if(ypos > 40)
{
topBar.classList.add("secondShrink");
}
else //ypos is 0
{
topBar.classList.remove("shrink");
topBar.classList.remove("secondShrink");
}
};
window.addEventListener("scroll", shrink)
#Top-Bar
{
height: 150px;
width: 100%;
background-color: #ccc;
display: flex;
justify-content: center;
align-items: center;
transition: all .2s ease;
position: fixed;
z-index: 2;
}
#Top-Bar.shrink
{
height: 100px;
transition: all .2s ease;
}
#Top-Bar.secondShrink
{
height: 50px;
}
.content
{
content: "";
height: 1200px;
position: relative;
z-index: 1;
}
<div id="Top-Bar">
<h1>Site Title</h1>
</div>
<div class="content"></div>
关于javascript - 动画导航栏上的增量收缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42723043/