如何从元素的像素中获取位置?

时间:2013-09-01 06:52:17

标签: jquery html css

我有一个UL元素,其中包含5个LI元素:

ul{
    width: 200px;
    height: 100%;
    padding: 0;
    margin: 0;
    overflow-y: auto;
    overflow-x: hidden;
    list-style: none;
    margin-left: 3px;
}

li{
    position: relative;
    height: 50px;
    width: 193px;
    left: 0;
    right: 0;
    margin: 10px 0;
    cursor: pointer;
}

我想从LI顶部获取每个UL顶部像素值,但是当我使用此代码时:

$('ul li').each(function(){
    console.log($(this).css('top'));
});

它只是告诉我这个:'auto',为什么?

2 个答案:

答案 0 :(得分:3)

您可以使用.position()。您还可以使用:nth-​​child选择特定的li。

$('ul li').each(function(){
   var position = $(this).position();

   console.log(position.top);
   console.log(position.left);
});

答案 1 :(得分:1)

如果要获取相对于文档的位置,请使用offset,使用position来获取相对于容器元素的位置。

$('ul li').each(function() {
   var position = $(this).position();    // to get top value relative to container
   position = $(this).offset();          // to get position top relative to document
});