jQuery - Follow the cursor with a DIV

前端 未结 3 1931
旧巷少年郎
旧巷少年郎 2020-11-28 21:04

How can I use jQuery to follow the cursor with a DIV?

3条回答
  •  余生分开走
    2020-11-28 21:32

    This works for me. Has a nice delayed action going on.

    var $mouseX = 0, $mouseY = 0;
    var $xp = 0, $yp =0;
    
    $(document).mousemove(function(e){
        $mouseX = e.pageX;
        $mouseY = e.pageY;    
    });
    
    var $loop = setInterval(function(){
    // change 12 to alter damping higher is slower
    $xp += (($mouseX - $xp)/12);
    $yp += (($mouseY - $yp)/12);
    $("#moving_div").css({left:$xp +'px', top:$yp +'px'});  
    }, 30);
    

    Nice and simples

提交回复
热议问题