如何在jquery中跟踪鼠标动画 [英] how to animate following the mouse in jquery

查看:157
本文介绍了如何在jquery中跟踪鼠标动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,这对于跟随我的鼠标非常合适。

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);
});
//

但我个人觉得从逻辑上说这应该有效!来自我的观点作为webscripter。 Amd然后我的问题是,我怎么能做这个工作。我希望#follower能够尝试跟随我的鼠标,带来一种动态的落后感觉。

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.

//
$(document).mousemove(function(e){
  $("#follower").animate({
      top: e.pageY + 'px';
      left: e.pageX + 'px';
  }, 800);
});
//


推荐答案

如何使用setInterval和一个叫做zeno悖论的公式:

How about using setInterval and an equation called zeno's paradox:

http:// jsfiddle.net/88526/1/

这就是我通常的做法。

根据要求,我已将代码包含在此答案中。鉴于具有绝对定位的div:

As requested, I've included the code in this answer. Given a div with absolute positioning:

CSS:

#follower{
  position : absolute;
  background-color : red;
  color : white;
  padding : 10px;
}

HTML:

<div id="follower">Move your mouse</div>

JS w / jQuery:

JS w/jQuery:

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);

这篇关于如何在jquery中跟踪鼠标动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆