简体   繁体   中英

Calculate direct (diagonal) distance from center of div to the center of the screen with jquery

Hej!

Is it possible to read / calculate the direct distance between the center of a div and the center of the screen with jquery?

I don't need the distance from the div to the vertical center of the screen (only giving me the distance in height) or to the horizontal center of the screen (only giving me the distance in width), but the diagonal distance.

Is this even possible with pixels?

Thanks for the help in advance, Kind regards

Lucas

This should work regardless of how scrolled down the page you are.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM