开发者

Can I get the coordinates of a div with JQuery?

the postion of the div on the p开发者_如何转开发age varies. How can I get the y position from the top?


jQuery('#id').offset()

Returns an object with top and left offsets.

http://api.jquery.com/offset/


So you have to options. position() or offset().

position() Basically similar to what you could use in the CSS top, left properties.

offset() Will return the distance relative to the document. This considers margins, paddings, and borders.

   <style>
     .cont {
        position: absolute;
        top: 100px;
        left: 100px;
        border: solid 3px black;
     }
     p { 
        margin: 20px; 
        padding: 20px; 
        border: solid 2px black;
        position: absolute; 
        top: 20px; 
        left: 20px; 
     }
    </style>

    <div class="cont">
         <p>Hello World!</p>
    </div>

    $('p').position() => { top: 20, left: 20 }
    $('p').offset() => { top: 143, left : 143 }

Notice how the position values are the same as the CSS values, and offset considers the position of the parent, the border of the parent and the element's ('p') margin and padding.

http://jsfiddle.net/4wfa6/

http://docs.jquery.com/CSS


You may also be interested in the position function which gets the position relative to an offset parent (vs offset which gets it relative to the document)

var position = $('#id').position();

http://api.jquery.com/position/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜