jQuery定位滚动导航效果是一种常见的网页交互设计,它允许用户在滚动页面时,导航栏能够固定在页面的某个位置,从而方便用户快速定位到页面的不同部分。下面是一个简单的示例代码,展示了如何使用jQuery实现这种效果:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Scroll Navigation</title>
<style>
body {
font-family: Arial, sans-serif;
}
.navbar {
position: fixed;
top: 0;
width: 100%;
background-color: #333;
overflow: hidden;
z-index: 1000;
}
.navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 20px;
text-decoration: none;
}
.navbar a:hover {
background-color: #ddd;
color: black;
}
.section {
height: 100vh;
padding-top: 60px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="navbar">
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
<a href="#section3">Section 3</a>
</div>
<div id="section1" class="section" style="background-color: #f1c40f;">
<h1>Section 1</h1>
</div>
<div id="section2" class="section" style="background-color: #2ecc71;">
<h1>Section 2</h1>
</div>
<div id="section3" class="section" style="background-color: #3498db;">
<h1>Section 3</h1>
</div>
<script>
$(document).ready(function(){
// 当滚动条滚动时触发
$(window).scroll(function(){
var scroll = $(window).scrollTop();
if (scroll > 50) {
$(".navbar").css("background-color", "#333");
} else {
$(".navbar").css("background-color", "transparent");
}
});
});
</script>
</body>
</html>
position: fixed;
属性,使得元素相对于浏览器窗口固定位置,不随页面滚动而移动。function throttle(func, wait) {
let timeout = null;
return function() {
const context = this;
const args = arguments;
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args);
}, wait);
}
};
}
$(window).scroll(throttle(function(){
var scroll = $(window).scrollTop();
if (scroll > 50) {
$(".navbar").css("background-color", "#333");
} else {
$(".navbar").css("background-color", "transparent");
}
}, 200));
通过上述代码,可以有效减少滚动事件的触发频率,避免导航栏闪烁问题。
领取专属 10元无门槛券
手把手带您无忧上云