简体   繁体   中英

How to get the left and top position of a child element of its parent

I have a parent-child structure of div elements (parent is the div called dartboard, a child div called rotatingDiv and that then has a child called crosshair).

dartboard
     > roatingDiv
            > crosshair

The dartboard container holds a rotating container (rotaingDiv), which then holds a child element (crosshair). I would like to find the x and y positions in relation to the dartboard container. Here is what I have at present:

$('#dartboard').append( $('#rotatingDiv').append( $('#crosshair') ) );

        X = $('#crosshair').position().left.toFixed(1) 
        Y = $('#crosshair').position().top.toFixed(1) 

console.log("x is "+X+", y is "+Y);

This process runs within a per-second timer, upon inspection of the x and y values, I've noticed that i'm only receiving this information in relation of the crosshair element being inside the rotatingDiv instead of being at the dartboard level (parent of parent). Does anyone know how I can do this?

Try this:

var parentLeft = $('#parent').offset().left,
    parentTop = $('#parent').offset().top
    childLeft = $('#child').offset().left,
    childTop = $('#child').offset().top;


// Positions respective to parent
var top = parentTop - childTop,
    left = parentLeft - childLeft;

You can also use position .

This should work:

var pos1 = $("#crosshair").position();
var pos2 = $("#crosshair").parent().position(); // or $('#rotatingDiv').position();

var x = (pos1.left + pos2.left ).toFixed(1);
var y = (pos1.top  + pos2.top  ).toFixed(1);

Be careful:

Note: jQuery does not support getting the position coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

You can check the API here .

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