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 导航跟随鼠标效果</title>
<style>
body {
height: 2000px;
margin: 0;
padding: 0;
}
.navbar {
position: absolute;
top: 0;
left: 0;
width: 100%;
background-color: #333;
color: white;
padding: 10px;
text-align: center;
transition: top 0.3s;
}
</style>
</head>
<body>
<div class="navbar">导航栏</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
var navbar = $('.navbar');
$(document).mousemove(function(event) {
var mouseY = event.clientY;
navbar.css('top', mouseY - navbar.outerHeight() / 2);
});
});
</script>
</body>
</html>
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);
}
};
}
$(document).mousemove(throttle(function(event) {
var mouseY = event.clientY;
navbar.css('top', mouseY - navbar.outerHeight() / 2);
}, 100));
$(document).mousemove(function(event) {
var mouseY = event.clientY;
var newTop = mouseY - navbar.outerHeight() / 2;
if (newTop < 0) {
newTop = 0;
} else if (newTop + navbar.outerHeight() > $(window).height()) {
newTop = $(window).height() - navbar.outerHeight();
}
navbar.css('top', newTop);
});
通过以上方法,可以实现一个流畅且用户体验良好的导航跟随鼠标上下滑动效果。
没有搜到相关的文章