Jquery偏移方法,用于数组中的所有元素,而不仅仅是第一个元素

时间:2012-10-18 08:38:58

标签: javascript jquery html offset

我在同一个页面上有几个div。我想使用jquery偏移方法来查找所有这些div的偏移量。

  

$(' DIV&#39)。偏移()

返回第一个div的偏移量。

但是,如果我想要所有div的偏移量,有没有办法做到这一点?

2 个答案:

答案 0 :(得分:11)

你必须迭代div:

$('div').each(function() {
     console.log($(this).offset());
});

答案 1 :(得分:4)

以@ dystroy的答案为基础:

var offsetCollection = new Array();
$('div').each(function() {
     offsetCollection.push(
       $(this).offset(), $(this).index()
     );
});

然后你可以:

offsetCollection[0][0]; //div 1, offset
offsetCollection[0][1]; //div 1, elementIndex