使用移动元素跟踪鼠标悬停事件

时间:2016-06-22 20:36:40

标签: javascript jquery html

我正在开发一个应用程序,并遇到了一个非常简单但令人沮丧的问题。基本上我有一个移动元素,我想跟踪它在鼠标上移动的时间。所以目前,如果指针位于屏幕中间并且当盒子经过时不移动,则将触发NO事件。是否有任何类型的鼠标或指针事件,当盒子经过它时会触发事件?

感谢。我写的简单代码示例如下:

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.0.0.js"></script>
</head>
<body>
    <div id="box" style="height:300px;width:300px;background-color:green;position:absolute;top:600px;"></div>
    <script>
    var box = document.getElementById('box');
    box.addEventListener('onmouseover',function(e){
    console.log('im being tagged!')
    });
    $('#box').animate({top: '1px'},3000);
    </script>
</body>
</html>

到目前为止我尝试过的事件:onmouseover,mouseover,mouseenter,mousemove,pointerenter,pointerover

指针事件来自名为pep的库。

3 个答案:

答案 0 :(得分:1)

由于您想知道移动的box元素何时与鼠标发生碰撞,反之亦然,因此您需要为该碰撞设置循环检查。您需要计算并保留鼠标光标的位置,并使用document.elementFromPoint检查光标上的元素是否为box

$(document).ready(function() {
  var MouseCoords = function(x, y) {
    this.x = x;
    this.y = y;
  };

  var mousecoords = new MouseCoords(0,0);
  var isTagged = false;

  $( document ).on( "mousemove", function( event ) {
    mousecoords.x = event.pageX;
    mousecoords.y = event.pageY;
  });

  $('#box').animate({top: '1px'},3000);

  function isBoxOverMouse() {
    var collidingElement = document.elementFromPoint(mousecoords.x, mousecoords.y);
    if (collidingElement != null && collidingElement.id == "box") {
      if (!isTagged) {
        isTagged = true;
        console.log("Tag!");
      }
    } else {
      isTagged = false;
    }
  }

  setInterval(isBoxOverMouse, 500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box" style="height:300px;width:300px;background-color:green;position:absolute;top:600px;"></div>

我将循环设置为每500毫秒触发一次,但如果这不是您想要的频率,则可以更改。我还设置了一个isTagged变量,因此控制台不会多次报告相同的碰撞,所以如果您希望在每个检查的时间间隔内报告碰撞,请随意删除它。

答案 1 :(得分:1)

调整此great answer to detect element collision

中的代码

我添加了一个在动画进行过程中运行的函数。喜欢这个

$('#box').animate({
    top: '1px'
  }, {
    duration: 5000,
    // check if box overlaps cursor while animating
    progress: function(promise) {
      isOverlapping(this);
    }
  });

有关详细信息,请参阅jQuery API docs

$(function() {
  var cursorX, cursorY = 0;

  // tracks mouse position and updates its x,y coordinates
  $(document).on('mousemove', function(e) {
    cursorX = e.pageX;
    cursorY = e.pageY;
    $("#cursor").text("[X: " + e.pageX + ", Y: " + e.pageY + "]");
    isOverlapping("#box");
  });

  // detects if two elements overlap
  var overlaps = (function() {
    function getPositions(elem) {
      var pos, width, height;
      pos = $(elem).position();
      width = $(elem).width();
      height = $(elem).height();
      return [
        [pos.left, pos.left + width],
        [pos.top, pos.top + height]
      ];
    }

    function comparePositions(p1, p2) {
      var r1, r2;
      r1 = p1[0] < p2[0] ? p1 : p2;
      r2 = p1[0] < p2[0] ? p2 : p1;
      return r1[1] > r2[0] || r1[0] === r2[0];
    }

    return function(b) {
      // making cursor 2x2 pixels
      var pos1 = [
          [cursorX, cursorX + 2],
          [cursorY, cursorY + 2]
        ],
        pos2 = getPositions(b);
      return comparePositions(pos1[0], pos2[0]) && comparePositions(pos1[1], pos2[1]);
    };
  })();

  // updates status if the box overlaps the cursor
  var isOverlapping = function(elem){
    if (overlaps(elem)) {
        $("#boxPos").text("Overlaps");
        $("#boxPos").addClass("yes");
        $("#boxPos").removeClass("no");
      } else {
        $("#boxPos").text("No overlap");
        $("#boxPos").addClass("no");
        $("#boxPos").removeClass("yes");
      }
    }

  $('#box').animate({
    top: '1px'
  }, {
    duration: 5000,
    // check if box overlaps cursor while animating
    progress: function(promise) {
      isOverlapping(this);
    }
  });
});
#cursor,
#boxPos {
  float: right;
  display: block;
}
.yes {
  background-color: green;
}
.no {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box" style="height:150px;width:150px;background-color:green;position:absolute;top:600px;"></div>
<div id="cursor"></div>
<br/>
<div id="boxPos"></div>
<br/>

答案 2 :(得分:0)

由于您使用的是JQuery,因此可以使用附加到HTML body元素的mousemove事件处理程序。这将为您提供鼠标位置,然后您可以使用它来确定鼠标何时与盒子相交。

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.0.0.js"></script>
</head>
<body>
    <div id="box" style="height:300px;width:300px;background-color:green;position:absolute;top:600px;"></div>
    <script>
    $(document).ready(function() {
        var mousePos = {x:0, y:0}
        $('html').mousemove(function(event) {
            mousePos.x = event.clientX
            mousePos.y = event.clientY
        })
        $('#box').animate({top: '1px'},{
            duration: 3000,
            step: function() {
                console.log(parseInt($('#box').css('top')) <= mousePos.y)
            }
        });
    })
    </script>
</body>
</html>