JQuery follow mouse curser within in a div centered on page

后端 未结 2 1200
执念已碎
执念已碎 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 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

提交回复
热议问题