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

标签 javascript jquery css html

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

我正在使用 jQuery 为一个 div 设置动画以使其向左移动,然后在我将鼠标悬停在该 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(){}) 中的任何内容都不会运行。我必须将鼠标移到元素上才能运行代码,而不是让元素移动到鼠标上。

如果我将鼠标悬停在该元素上,然后让鼠标闲置,也会发生同样的事情。 $('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 检查悬停状态的时候。因此,我们需要模拟确定悬停的事件并重复调用它,即使光标没有移动以确保悬停状态已更新。

关于javascript - jQuery:检查鼠标是否在动画上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36380040/

相关文章:

javascript - 获取坐标事件 map openlayers 4.6.5 ~ 5

javascript - 数组ng-options循环数组找不到值

javascript - 通过 jQuery 提交表单时 Required 不起作用?

java - 如何使用modelAttribute在ajax(jquery)中提交spring表单

html - 当 div 内容改变并且 div 增长时 CSS3 转换

html - 在 div/图像右侧 float 文本

javascript - VueJS 语法 : Saving a value in a Promise

javascript - 在 php 中接收 JavaScript 值时出错

javascript - 在 JavaScript 中使用 typeof 仍然会导致 undefined object 的错误

html - Bootstrap 网格系统中的表格