Javascript 如何在jquery中跟随鼠标动画
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4847726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to animate following the mouse in jquery
提问by Joshua Robison
OK, this works perfectly fine for following my mouse.
好的,这非常适合跟随我的鼠标。
//
$(document).mousemove(function(e){
$("#follower").css({
'top': e.pageY + 'px';
'left': e.pageX + 'px';
});
});
//
And this works great for animating the mouse to a clicked point
这非常适合将鼠标设置为单击点的动画
//
$(document).click(function(e){
$("#follower").animate({
top: e.pageY + 'px';
left: e.pageX + 'px';
}, 800);
});
//
But I personally feel that logically this SHOULD work! Coming from my point of view as the webscripter. Amd then my question is, how can I make this work. I want the #follower to try and follow my mouse with a dynamic kind of lagging behind feel.
但我个人认为,从逻辑上讲,这应该可行!从我作为 webscripter 的角度来看。那么我的问题是,我怎样才能做到这一点。我希望#follower 尝试以一种动态的落后感觉跟随我的鼠标。
//
$(document).mousemove(function(e){
$("#follower").animate({
top: e.pageY + 'px';
left: e.pageX + 'px';
}, 800);
});
//
回答by Zevan
How about using setInterval and an equation called zeno's paradox:
如何使用 setInterval 和一个称为芝诺悖论的方程:
That's the way I usually do it.
这就是我通常这样做的方式。
As requested, I've included the code in this answer. Given a div with absolute positioning:
根据要求,我已将代码包含在此答案中。给定一个具有绝对定位的 div:
CSS:
CSS:
#follower{
position : absolute;
background-color : red;
color : white;
padding : 10px;
}
HTML:
HTML:
<div id="follower">Move your mouse</div>
JS w/jQuery:
带有 jQuery 的 JS:
var mouseX = 0, mouseY = 0;
$(document).mousemove(function(e){
mouseX = e.pageX;
mouseY = e.pageY;
});
// cache the selector
var follower = $("#follower");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 12 to alter damping, higher is slower
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
follower.css({left:xp, top:yp});
}, 30);