jQuery:检查鼠标是否在动画上?

这就是我正在做的事情: https : //jsfiddle.net/atg5m6ym/2625/

我正在使用jQuery动画div向左移动,然后当我将鼠标hover在div上并且当我将鼠标移离它时登录到控制台:

$("div").animate({left: '250px'}, 6000); $('div').hover(function() { console.log("Mouse hovered on div!"); }).mouseleave(function() { console.log("Mouse left div!"); }) 

当然,该程序将运行console.log("Mouse hovered on div!"); 一旦我把鼠标放在元素上。

但是,如果我让鼠标闲置并且动画元素移动到它上面,那么$('div').hover(function(){})都不会运行。 我必须将鼠标移动到元素上才能运行代码,而不是让元素来到鼠标。

如果我将鼠标hover在元素上,然后让鼠标闲置,也会发生同样的事情。 $('div').mouseleave(function(){})都将在元素离开后运行,直到我将鼠标从其位置移开。

有什么方法可以解决这个问题吗? 我正在使用动画div,即使鼠标处于空闲状态并且div通过它,我也需要运行代码。

手动获取鼠标的最后已知位置,并将其与圆的位置进行比较。 这有点广泛但它应该能为您带来正确的结果。

这是一个JSFiddle: https ://jsfiddle.net/3vpaoj59/

 $("div").animate({left: '250px'}, 6000); $(document).ready(function() { // record down the position of the cursor var cursorX; var cursorY; document.onmousemove = function(e){ cursorX = e.pageX; cursorY = e.pageY; } // boolean to know if hovered or not, and to know whether to report in console.log var hover = false; // function to call by setinterval to check if mouse is within radius function checkMouse(){ // find the centerpoint of the circle by taking its position then adding half its width/height to each coordinate var left = $("#foo").offset().left+$("#foo").width()/2; var top = $("#foo").offset().top+$("#foo").height()/2; // use pythagorean theorem to find distance between two points var xdist = Math.pow(Math.abs(cursorX - left),2); var ydist = Math.pow(Math.abs(cursorY - top),2); var hypotenuse = Math.round(Math.sqrt(xdist+ydist)); // check if the distance is less than radius if(hypotenuse <= $("#foo").width()/2 && !hover){ // if true and not already reported true, report then fix console.log("mouse hovered on div!"); hover = true; } else if (hypotenuse > $("#foo").width()/2 && hover){ // if false and not already reported false, report then fix console.log("mouse left div!"); hover = false; } } // repeatedly call this setInterval(checkMouse, 100); }); 

为方便起见,我将div的ID更改为“foo”。 确保也这样做,以便代码适用于您的项目,或修改JS不使用“foo”。

说明:

您的问题发生的原因是因为您的鼠标的坐标只在每次移动光标时更新,而且当hover状态由.hover检查.hover 。 因此,我们需要模拟确定hover的事件并重复调用它,即使光标未移动以确保更新hover状态。