计算鼠标和 DOM 元素边缘之间的距离



我想计算鼠标和给定元素的边缘之间的距离。因此,当鼠标触摸元素的边缘时,值应为 0px;

https://codepen.io/nishaljohn/pen/BVmGbz

var mX, mY, distance,
$distance = $('#distance_text p'),
$element  = $('.div1');
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);         
});

这考虑了元素的中心,并且仅当您到达绝对中心时才读取 0px。

JQuery插件也可以。

对于任何大小的元素,我使用了我在另一个示例中找到的以下代码:

var mX = e.pageX;
var mY = e.pageY;
var from = {x:mX, y:mY};
var $n=your_Element;
var off = $n.offset(),
nx1 = off.left,
ny1 = off.top,
nx2 = nx1 + $n.outerWidth(),
ny2 = ny1 + $n.outerHeight(),
maxX1 = Math.max(mX, nx1),
minX2 = Math.min(mX, nx2),
maxY1 = Math.max(mY, ny1),
minY2 = Math.min(mY, ny2),
intersectX = minX2 >= maxX1,
intersectY = minY2 >= maxY1,
to = {
x: intersectX ? mX : nx2 < mX ? nx2 : nx1,
y: intersectY ? mY : ny2 < mY ? ny2 : ny1
};
var distX = to.x - from.x,
distY = to.y - from.y,
hypot = Math.sqrt(distX * distX + distY * distY);
console.log(hypot);//this will output 0 when next to your element.

好的,解决方案只是纯粹的数学。它即将带走容器的宽度和高度- elem.width()/2- elem.height()/2

(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) - elem.width()/2 + Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2) ) -elem.height()/2);
}
$(document).mousemove(function(e) {  
mX = e.pageX;
mY = e.pageY;
distance = calculateDistance($element, mX, mY);
if(distance > 0)
	$distance.text(distance);
else{
$distance.text(0);
}
});
})();
body {
font: 11px helvetica, arial, sans-serif;
text-align: center;    
}
#distance {
font-size: 16px;
font-weight: bold; 
margin-top: 10px; 
}
#element {
background: #000;
color: #fff;
height: 50px;
left: 50%;
margin: -25px 0 0 -25px;
position: absolute;
top: 50%;
width: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Move your mouse to calculate distance between the center of the element and the mouse cursor.</p>
<p id="distance">Distance: <span>0</span>px</p>
<div id="element"></div>

这是解决方案吗?

最新更新