当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - 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?

网友答案:

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.

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: