实例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>网页头部导航滚动显隐</title>
<style>
* {
margin: 0;
padding: 0;
text-align: center;
}
.header {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 60px;
line-height: 60px;
color: white;
background: linear-gradient(rgb(0, 110, 255), black, rgb(0, 110, 255));
}
.main {
height: 1000px;
line-height: 100px;
}
.footer {
height: 60px;
line-height: 60px;
color: white;
background: linear-gradient(rgb(60, 255, 0), black, rgb(60, 255, 0));
}
</style>
</head>
<body>
<header class="header">头部导航</header>
<main class="main">主体内容</main>
<footer class="footer">底部信息</footer>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function () {
// 滚动条初始高度
let High = 0;
// 定时器
let Time = null;
// 窗口滚动条事件
$(window).scroll(() => {
// 向上滑动触发
if ($(window).scrollTop() <= H) {
clearTimeout(Time);
Time = setTimeout(() => {
$('.header').slideDown();
$('body').css('paddingTop', '60px');
High = $(window).scrollTop();
}, 300);
} else {
// 向下滑动触发
clearTimeout(Time);
Time = setTimeout(() => {
$('.header').slideUp();
$('body').css('paddingTop', '0');
High = $(window).scrollTop();
}, 300);
}
});
});
</script>
</body>
</html>