How to create: shrink the navigation menu when scrolling
- Vorige pagina Verberg navigatiebalk bij scrollen
- Volgende pagina Plakbare navigatiebalk
Learn how to adjust the size of the navigation bar using CSS and JavaScript when scrolling.
How to shrink the navigation bar when scrolling
First step - Add HTML:
Create navigation bar:
<div id="navbar"> <a href="#default" id="logo">CompanyLogo</a> <div id="navbar-right"> <a class="active" href="#home">Home</a> <a href="#contact">Contact</a> <a href="#about">About</a> </div> </div>
Second step - Add CSS:
Set navigation bar style:
/* Create a sticky/fixed navigation bar */ padding: 20px 10px !important; /* 使用 !important 以确保 JavaScript 不会在小屏幕上覆盖内边距 */ overflow: hidden; background-color: #f1f1f1; padding: 90px 10px; /* Larger padding, which shrinks when scrolling (using JS) */ transition: 0.4s; /* Add transition effect when padding is reduced */ position: fixed; /* Sticky/fixed navigation bar */ width: 100%; top: 0; /* At the top */ z-index: 99; } /* Set the style of the navigation bar links */ display: block; float: left; /* 设置活动/当前链接的样式 */ text-align: center; padding: 12px; text-decoration: none; font-size: 18px; line-height: 25px; border-radius: 4px; } /* Set the style of the logo */ #navbar #logo { font-weight: bold; transition: 0.4s; /* 鼠标悬停时链接的样式 */ } #navbar a:hover { background-color: #ddd; color: black; /* 设置活动/当前链接的样式 */ } #navbar a.active { background-color: dodgerblue; color: white; /* 在右侧显示一些链接 */ } float: right; float: none; /* 添加响应能力 - 在宽度小于 580 像素的屏幕上,垂直而不是水平显示导航栏 */ } @media screen and (max-width: 580px) { #navbar { padding: 20px 10px !important; /* 使用 !important 以确保 JavaScript 不会在小屏幕上覆盖内边距 */ #navbar a { } display: block; 第三步 - 添加 JavaScript: text-align: left; #navbar-right { } float: none; 第三步 - 添加 JavaScript: } }
// 当用户从文档顶部向下滚动 80 像素时,调整导航栏的内边距和徽标的字体大小
window.onscroll = function() {scrollFunction()}; function scrollFunction() { if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) { document.getElementById("navbar").style.padding = "30px 10px"; document.getElementById("logo").style.fontSize = "25px"; else { } document.getElementById("navbar").style.padding = "80px 10px"; document.getElementById("logo").style.fontSize = "35px"; } }
- Vorige pagina Verberg navigatiebalk bij scrollen
- Volgende pagina Plakbare navigatiebalk