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

时间:2018-06-18 09:20:32

标签: javascript jquery html jquery-ui jquery-plugins

我想计算鼠标和给定元素的边缘之间的距离。因此,当鼠标触摸元素的边缘时,该值应为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插件也没关系。

2 个答案:

答案 0 :(得分:0)

好的解决方案只是纯数学。它即将带走容器的宽度和高度.katex { font-size: 1em !important; } - 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;
}

这是解决方案吗?

答案 1 :(得分:0)

对于Square @ Cristian的回答很好,老实说是最好的。但对于任何Shape或size元素,我使用了我在另一个插件示例中找到的代码。 不完全确定数学如何运作但确实如此。

            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.