jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。跟随鼠标移动的效果通常是指一个元素(如一个图标或提示框)随着鼠标的移动而实时改变位置。
跟随鼠标移动的效果可以通过多种方式实现,常见的类型包括:
这种效果常用于:
以下是一个简单的示例,展示如何使用 jQuery 实现一个跟随鼠标移动的元素:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Follow Mouse</title>
<style>
#follower {
position: absolute;
width: 50px;
height: 50px;
background-color: red;
}
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="follower"></div>
<script>
$(document).ready(function() {
$(document).mousemove(function(event) {
$('#follower').css({
left: event.pageX,
top: event.pageY
});
});
});
</script>
</body>
</html>
requestAnimationFrame
来优化动画效果。$(document).mousemove(function(event) {
requestAnimationFrame(function() {
$('#follower').css({
left: event.pageX,
top: event.pageY
});
});
});
function throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
$(document).mousemove(throttle(function(event) {
$('#follower').css({
left: event.pageX,
top: event.pageY
});
}, 100));
通过以上方法,可以有效解决跟随鼠标移动效果中可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云