JQuery follow mouse curser within in a div centered on page

后端 未结 2 1199
执念已碎
执念已碎 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);
    
    0 讨论(0)
  • 2020-12-22 11:00

    You can use jQuery's .offset() to get the position of the element relative to the document, then subtract its left and top from the e.pageX and e.pageY values, respectively.

    To ensure it stays within the box, you need a lower bound on the mouseX and mouseY values. You could use Math.max or the ifs like I used below.

    $(window).mousemove(function(e){
      var offset = $('.container').offset();
       mouseX = Math.min(e.pageX - offset.left, limitX);
       mouseY = Math.min(e.pageY - offset.top, limitY);
       if (mouseX < 0) mouseX = 0;
       if (mouseY < 0) mouseY = 0;
    });
    

    JSFiddle demo

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