当元素被编程鼠标移到下悬停的jQuery不会触发 [英] jQuery hover not triggered when element is programatically moved under the mouse

查看:135
本文介绍了当元素被编程鼠标移到下悬停的jQuery不会触发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个悬停效果的图像(高不透明度时鼠标移动到它)。它的工作原理是当需要时鼠标移动和缩小。

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.

不过,本身是移动图像(我周期性地改变CSS属性的顶部)。当鼠标不移动,图像鼠标光标下运行,没有相关的事件被触发。这意味着,悬停功能不叫。我也尝试使用的mouseenter和鼠标离开事件,而不是,但他们不能工作。

However, the image itself is moving (I'm periodically changing the css attribute top). When the mouse does not move and the image moves under the mouse cursor, no related events are triggered. That means, the hover functions are not called. I also tried using the mouseenter and mouseleave events instead, but they don't work either.

这将是一个很好的方法来获得所需的行为(只要鼠标移动到图片悬停效果,不管它为什么到了那里)?

What would be a good approach to get the desired behavior (hover effect whenever the mouse is over the image, regardless of why it got there)?

推荐答案

您将无法触发如果鼠标不动鼠标事件,但您将能够以检查鼠标当图像移动。你需要做的是跟踪一个全局变量鼠标的位置,然后检查,看看是否能立场是你的形象里移动时。

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有关于如何使用他们的图书馆做一个漂亮的文章: HTTP://docs.jquery。 COM /教程:Mouse_Position

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

要找到你的形象,你可以使用jQuery的位置功能位置: HTTP://api.jquery。 COM /位置/

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.

这是我会怎么写code(完全未经测试BTW 的):

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...
  }
});

这篇关于当元素被编程鼠标移到下悬停的jQuery不会触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆