Home  >  Article  >  Web Front-end  >  jquery计算鼠标和指定元素之间距离的方法_jquery

jquery计算鼠标和指定元素之间距离的方法_jquery

WBOY
WBOYOriginal
2016-05-16 15:52:341999browse

本文实例讲述了jquery计算鼠标和指定元素之间距离的方法。分享给大家供大家参考。具体实现方法如下:

(function() {
  var mX, mY, distance,
    $distance = $('#distance span'),
    $element = $('#element');
  function calculateDistance(elem, mouseX, mouseY) {
    return Math.floor(Math.sqrt(Math.pow(mouseX - (elem.offset().left+(elem.width()/2)), 2) + Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
  }
  $(document).mousemove(function(e) { 
    mX = e.pageX;
    mY = e.pageY;
    distance = calculateDistance($element, mX, mY);
    $distance.text(distance);     
  });
})();

希望本文所述对大家的jQuery程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn