获取元素的坐标

时间:2011-12-24 15:07:05

标签: jquery

要获取鼠标的坐标,我们使用e.pageY和e.pageX。课程或身份证怎么样?它应该看起来像:

$(this).pageY;或类似的东西?它甚至可以吗?感谢。

4 个答案:

答案 0 :(得分:2)

offset()方法返回元素的位置(顶部和左侧)。

var offset = $("selector").offset();
offset.top   // Top position, relative to the top of the page
offset.left  // Left position, relative to the left of the page

答案 1 :(得分:2)

您可以根据自己的需要使用positionoffsetposition将为您提供相对于偏移父项的元素位置,offset将为您提供相对于文档的位置。

答案 2 :(得分:2)

如果你想获得某个元素相对于文档的坐标,即表示内容的整个页面,你可以使用offset()方法。否则,如果要获取相对于父元素的坐标,可以使用position()方法。这两个函数都返回元素的顶部和左侧。

   var absolute_coordinates = $('#mydiv').offset(); // top and left with respect to document

   var relative_coordinates = $('#mydiv').position(); //top and left with respect to parent 

   alert('#mydiv is ' + relative_coordinates.top
          + 'px below from parent and absolute_coordinates.top + 
         'px below from document');

答案 3 :(得分:1)

使用偏移量

$(".divItem").click(function(){
    alert("Left is : "+$(this).offset().left)
});

以下是一个示例:http://jsfiddle.net/ZBeWq/4/