JQuery follow mouse curser within in a div centered on page

后端 未结 2 1198
执念已碎
执念已碎 2020-12-22 09:56

I have followed some wonderful code to have an image follow the mouse cursor within a div container at http://jsfiddle.net/fhmkf/. The problem is, this method only works for

2条回答
  •  佛祖请我去吃肉
    2020-12-22 10:50

    Very nice example i needed this. Use your centerdiv to trigger the effect to save some performance and use position() and margin() to determine the real location of your div.

    var mouseX = 0, mouseY = 0, limitX = 150-15, limitY = 150-15;
    var stage = $(".centerdiv"), position = stage.position();
    
    stage.mousemove(function(e){
       mouseX = Math.min(e.pageX - position['left'], limitX);
       mouseY = Math.min(e.pageY - position['top'], limitY);
    });
    
    // 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);
    

提交回复
热议问题