how to animate following the mouse in jquery

前端 未结 1 764
温柔的废话
温柔的废话 2020-12-05 08:32

OK, this works perfectly fine for following my mouse.

//
$(document).mousemove(function(e){
  $(\"#follower\").css({
      \'top\': e.pageY + \'px\';
      \         


        
1条回答
  •  伪装坚强ぢ
    2020-12-05 09:08

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

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

    That's the way I usually do it.

    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:

    Move your mouse

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

    0 讨论(0)
提交回复
热议问题