Вопрос

I have section and article for displaying contents. My code is:

<section id = "examples">

 <article id="item_1">
    ...
 </article>

 <article id="item_2">
  ...
 </article>

 <article id="item_3">
    ...
 </article>

 <article id="item_4">
  ...
 </article>

 ...

</section>

How can I get the x and y co-ordinates of all the articles?

Это было полезно?

Решение 3

You could do it with jQuery using position or offset:

$('article').each(function(){
     var position = $(this).position();
     console.log("top: " + position.top + " left: " + position.left);
});

LIVING DEMO

Take into account that position is relative to the document and offset calculates the coordinates relative to the parent offset element.

Другие советы

Easy to do with jQuery

$('article').each(function() {
    var element = $(this);
    var position = element.position();
    console.log( "left: " + position.left + ", top: " + position.top );
}

you can use instead pure js as @koningdavid pointed out in the same way

var elements = document.getElementsByTagName('article');
for(var i = 0; i < elements.length; i++)
{
    var element = elements[i].getBoundingClientRect();
    console.log( "left: " + element.left + ", top: " + element.top );
}

Live: http://jsfiddle.net/HMHbE/1/

Pure Javascript method

document.querySelector('#item_1').getBoundingClientRect() // for example for #item_1

element.getBoundingClientRect

The returned value is a TextRectangle object which is the union of the rectangles returned by getClientRects() for the element, i.e., the CSS border-boxes associated with the element.

The returned value is a TextRectangle object, which contains read-only left, top, right and bottom properties describing the border-box, in pixels, with the top-left relative to the top-left of the viewport.

https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect

I would try this in javascript:

// element is each article
// then you can use element.top and element.left for the x and y
var element = document.getElementById('Item_1');
var ele = element.getBoundingClientRect();: 

You can use getBoundingClientRect() javascript function

 var div = document.getElementById("item_1");
 var position = div.getBoundingClientRect();
 alert("Coordinates: " + position.left + "px," + position.right+"px,"+ position.top + "px," + position.bottom + "px" );
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top