jQuery 页面滚动顶部悬浮导航是一种网页设计技术,通过在用户滚动页面时固定导航栏在页面顶部,从而提供更好的用户体验。这种导航栏通常包含网站的 logo、主要菜单和一些辅助功能按钮。
以下是一个使用 jQuery 实现固定定位悬浮导航栏的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 悬浮导航栏</title>
<style>
body {
height: 2000px; /* 用于测试滚动效果 */
}
.navbar {
position: relative;
background-color: #333;
color: white;
padding: 10px 20px;
text-align: center;
}
.fixed-navbar {
position: fixed;
top: 0;
width: 100%;
z-index: 1000;
}
</style>
</head>
<body>
<div class="navbar">导航栏</div>
<div style="height: 1000px; background-color: #eee;">内容区域</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
var navbar = $('.navbar');
var sticky = navbar.offset().top;
$(window).scroll(function() {
if ($(window).scrollTop() >= sticky) {
navbar.addClass('fixed-navbar');
} else {
navbar.removeClass('fixed-navbar');
}
});
});
</script>
</body>
</html>
.fixed-navbar
类。padding-top
属性为内容区域添加顶部间距。通过以上方法,可以有效地实现和优化 jQuery 页面滚动顶部悬浮导航栏的功能。
领取专属 10元无门槛券
手把手带您无忧上云