javascript - 动画导航栏上的增量收缩

标签 javascript jquery html css

我创建了一个固定的动画导航栏,它会在滚动时缩小。目前,如果 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.

我已经修改了下面的代码,以便一次只有一个缩水贴在顶部栏上。此外,您的 ifif else 不考虑 1-1039-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/

相关文章:

javascript - jQuery 函数不适用于动态生成的内容

javascript - Firefox 3.6 <label><p> 渲染问题

javascript - 删除没有内部内容Javascript的内部html标签

javascript - 如何在 HTML 中为样式使用变量

javascript - 如何更改输入类型 ="datetime-local"的格式?

javascript - 在Select2中出现Cannot read property 'createTextRange' of undefined

javascript - 用于密码验证的 Javascript 中的正则表达式

javascript - 对具有固定位置值的 DOM 元素进行排序(例如 : left:20px)

javascript - 在 JavaScript 中限制对 'style' 属性的访问

javascript - 几秒钟后显示/隐藏 HTML 移动按钮