Follow mouse on hover using animate Jquery

馋奶兔 提交于 2021-02-07 10:31:16

问题


I'm trying to achieve this mousemove effect over the images.
The images seem like it's following my mouse,I'm trying to follow it and so far this. I tried this example https://jsfiddle.net/lesson8/SYwba/. But I'm stuck on combining it with my current fiddle.

This is my desired output.Like the images is following the mouse. Output

$('.animated').hover(
    function() {
        $('.animated').animate({
            marginTop:20
        });
    },
    function() {
        $('.animated').animate({
            marginTop:10
        });
    }
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<img class="animated" src="http://via.placeholder.com/350x150"/>

Also tried this:

$(document).mousemove(function(e) {
    $('.logo').offset({
        left: e.pageX,
        top: e.pageY + 20
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<img class="logo" src="//ssl.gstatic.com/images/logos/google_logo_41.png" alt="Google">

回答1:


The logic is actually quite simple: what you want to do is to offset the image away from its original position based on the relative position of the cursor in the document/viewport. We will need to perform all this calculations in the mousemove event on document.

$(document).on('mousemove', function(e) {...});

Also, this means that you will need some following information:

  1. determine the maximum offset you want the image to be moved from its original position
  2. the viewport width and height
  3. the mouse/cursor position relative to viewport height—that will give us a range of [0, 1]
  4. transform that range to [-1, 1], since negative values are used to move to the top/left and positive values used to move to the bottom/right
  5. use CSS3 transform to move the image

Step-by-step guide

1. Determine maximum offset

Let's say we want to restrict the movement to ±30px. We can define them as:

// Maximum offset for image
var maxDeltaX = 30,
    maxDeltaY = 30;

2. Get viewport dimensions

Viewport dimensions can be accessed by document.documentElement.clientWidth/clientHeight:

// Get viewport dimensions
var viewportWidth = document.documentElement.clientWidth,
    viewportHeight = document.documentElement.clientHeight;

3 and 4. Get the relative position of the cursor to the viewport

The key here is to calculate the relative position of the cursor to the viewport. First, we get the fraction of the mouse/cursor coordinates to the viewport, which will give us a range of [0, 1]. However, we need to transform this into [-1, 1], so that we can calculate left/top movement (using negative values) and bottom/right movement (using positive values). The arithmetic transformation from [0, 1] to [-1, 1] is simply multiplying to 2 (so you get [0, 2]) and minus 1 (then you get [-1, 1]):

// Get relative mouse positions to viewport
var mouseX = e.pageX / viewportWidth * 2 - 1,
    mouseY = e.pageY / viewportHeight * 2 - 1;

5. Use CSS3 transform to position your image

This is the most straight forward part. The amount to translate is simply mouseX × maxDeltaX and the same along the y-axis. We pass these values into transform: translate(<x>px, <y>px):

// Calculate how much to transform the image
var translateX = mouseX * maxDeltaX,
    translateY = mouseY * maxDeltaY;
$('.animated').css('transform', 'translate('+translateX+'px, '+translateY+'px)');

Working example

See proof-of-concept below:

// Settings
// Maximum offset for image
var maxDeltaX = 30,
    maxDeltaY = 30;

// Bind mousemove event to document
$(document).on('mousemove', function(e) {

  // Get viewport dimensions
  var viewportWidth = document.documentElement.clientWidth,
      viewportHeight = document.documentElement.clientHeight;

  // Get relative mouse positions to viewport
  // Original range: [0, 1]
  // Should be in the range of -1 to 1, since we want to move left/right
  // Transform by multipling by 2 and minus 1
  // Output range: [-1, 1]
  var mouseX = e.pageX / viewportWidth * 2 - 1,
      mouseY = e.pageY / viewportHeight * 2 - 1;
      
  // Calculate how much to transform the image
  var translateX = mouseX * maxDeltaX,
      translateY = mouseY * maxDeltaY;
  $('.animated').css('transform', 'translate('+translateX+'px, '+translateY+'px)');
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<img class="animated" src="http://via.placeholder.com/350x150"/>



回答2:


Try binding hover event to only div or some container in which you want to move the image instead of image itself.

$('.wrapper-div').hover();



回答3:


I'll just give you a hint

$('.animated').mousemove(
  function(ev) {
    document.getElementById("MouseCoord").innerHTML = ev.clientX + ':' + ev.clientY;
  }
);

window.addEventListener("load", function() {
  var rect = document.getElementById("container").getBoundingClientRect();
  // .toFixed(0) only remove decimal part for a nice display
  document.getElementById("BoxSize").innerHTML = 
    "Box is at (" + rect.left.toFixed(0) + ";" + rect.top.toFixed(0) + ")" +
    " with size " + rect.width.toFixed(0) + "x" + rect.height.toFixed(0);
});
#container {
  width: 400px;
  height: 200px;
  border: .1px solid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p id="MouseCoord">-</p>
<p id="BoxSize">-</p>
<div id="container">
  <img class="animated" src="http://via.placeholder.com/350x150" />
</div>


来源:https://stackoverflow.com/questions/46687538/follow-mouse-on-hover-using-animate-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!