jQuery x y document coordinates of DOM object

前端 未结 3 1882
陌清茗
陌清茗 2020-11-27 13:36

I need to get the X,Y coordinates (relative to the document\'s top/left) for a DOM element. I can\'t locate any plugins or jQuery property or method that can give these to

3条回答
  •  被撕碎了的回忆
    2020-11-27 13:57

    you can use Dimensions plugin [Deprecated... included in jQuery 1.3.2+]

    offset()
    Get the current offset of the first matched element, in pixels, relative to the document.

    position()
    Gets the top and left position of an element relative to its offset parent.

    knowing this, then it's easy... (using my little svg project as an example page)

    var x = $("#wrapper2").offset().left;
    var y = $("#wrapper2").offset().top;
    
    console.log('x: ' + x + ' y: ' + y);
    

    output:

    x: 53 y: 177
    

    hope it helps what you're looking for.

    here's an image of offset() and position()

    using XRay

    alt text

    using Web Developer toolbar

    alt text

提交回复
热议问题