javascript - 滚动页面后更改导航栏
问题描述
我想知道滚动页面后如何更改导航栏。
开始情况,一旦用户到达网站,他就会找到一个导航栏,一旦他滚动页面,另一个导航栏就会立即出现,就像在这个主题中发生的那样: https://kendall.qodeinteractive.com/manicure/
解决方案
有多种方法可以做到这一点,但最简单的是使用两个导航栏。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Navbar</title>
<style>
*,
*:before,
*:after {
margin: 0;
font-family: sans-serif;
}
section {
width: 100%;
height: 2500px;
}
.header {
box-sizing: border-box;
position: absolute;
top: 0;
width: 100%;
height: 400px;
text-align: center;
background-color: #33f;
color: #fff;
}
.navigation {
box-sizing: border-box;
position: fixed;
width: 100%;
height: 60px;
background-color: #ff4d4d;
color: #fff;
padding: 20px 50px;
transition: all 0.5s ease;
transform: translateY(-100%);
z-index: 9999;
}
.navigation--relative {
position: relative;
top: 0px;
transform: translateY(0%);
}
.navigation.is-fixed {
position: fixed;
width: 100%;
transform: translateY(0%);
}
</style>
</head>
<body>
<section>
<nav class='navigation'>
<div class='navigation__title'><h1>Navbar 1</h1></div>
</nav>
<header class='header header-content'>
<nav class='navigation navigation--relative'>
<div class='navigation__title'><h1>Navbar 2</h1></div>
</nav>
<h1>Content</h1>
</header>
</section>
<script>
function stickyElement(e) {
var header = document.querySelector('.header');
var headerHeight = getComputedStyle(header).height.split('px')[0];
var navbar = document.querySelector('.navigation');
var scrollValue = window.scrollY;
if (scrollValue > headerHeight) {
navbar.classList.add('is-fixed');
} else if (scrollValue < headerHeight) {
navbar.classList.remove('is-fixed');
}
}
window.addEventListener('scroll', stickyElement);
</script>
</body>
</html>
推荐阅读
- git - Git 强制将 dev 分支合并到 master 分支(覆盖所有本地文件)
- java - 如何使用 HttpURLConnection 为 java android 发送身份验证密钥?我收到错误代码 500
- strapi - 无法使用 Strapi 在生产模式下创建新条目
- c# - 如何使用 EntityFramework Core 在两个模块之间创建关系?
- python - 从平面词典创建嵌套词典
- python-3.x - 在课堂上调用和打印时遇到问题
- django - 浏览器拨打电话时出现 Twilio 12100 错误
- typescript - 如何从抽象类的静态方法创建具体类的实例
- python - 用于搜索 Pandas 数据框的 Python 函数
- servicestack - ServiceStack OrmLite Text blobbed 值被检索为 null