jQuery hover not triggered when element is programatically moved under the mouse

后端 未结 4 618
星月不相逢
星月不相逢 2021-01-02 22:16

I have an image with a hover effect (higher opacity when mouse is over it). It works as desired when the mouse moves in and out.

However, the image itself is moving

4条回答
  •  情话喂你
    2021-01-02 22:48

    You won't be able to trigger mouse events if the mouse isn't moving, though you will be able to check where the mouse is when the image is moving. What you need to do is track the mouse position in a global variable, and check to see if that position is inside your image when it moves.

    jQuery has a nice article about how to do it using their library: http://docs.jquery.com/Tutorials:Mouse_Position

    To find the position of your image you can use the jQuery position function: http://api.jquery.com/position/

    With that position you can create a bounds using the height/width of your image. On your image move check to see if that global mouse position is inside your image bounds and you should be good to go.

    This is how I would write the code(completely untested btw):

    var mousex = 0;
    var mousey = 0;
    
    jQuery(document).ready(function(){
       $(document).mousemove(function(e){
          mousex = e.pageX;
          mousey = e.pageY;
       }); 
    })
    
    img.move(function(){
      ...move code...
      var p = $(this).position();
      if(mousex >= p.left && mousex <= p.left + $(this).width
         && mousey <= p.top && mousey >= p.top + $(this).height)
      {
       ...opacity code...
      }
    });
    

提交回复
热议问题