使用jquery计算从div中心到屏幕中心的直接(对角线)距离

时间:2017-03-03 07:40:24

标签: javascript jquery distance

HeJ小鼠!

是否可以使用jquery读取/计算div的中心与屏幕中心之间的直接距离?

我不需要从div到屏幕垂直中心的距离(只给我高度的距离)或屏幕的水平中心(只给我宽度的距离),但是对角线距离。

这是否可以用像素?

感谢您的帮助, 亲切的问候

卢卡斯

1 个答案:

答案 0 :(得分:0)

无论您向下滚动页面如何,这都应该有效。

let element = document.getElementById("someId");
let elementPosition = getCenterOfElement(element);
let documentPosition = getCenterOfPage();
let result = calculateDistance(documentPosition , elementPosition);

function getCenterOfPage() {
    let x = $(document).width()/2;
    let y = $(document).height()/2;
    let coordinates = {x, y};
    return coordinates;
}
function getCenterOfElement(element) {
    let x = $(element).offset().left + $(element).outerWidth()/2;
    let y =  $(element).offset().top + $(element).outerHeight()/2;
    let coordinates = {x, y};
    return coordinates;
}
function calculateDistance(coordinates1, coordinates2) {
    let h = coordinates1.x - coordinates2.x;
    let v = coordinates1.y - coordinates2.y;
    let result = Math.sqrt(h*h + v*v);
    return result;
}