开发者

jquery offset() and position()

开发者 https://www.devze.com 2023-02-11 12:40 出处:网络
I need to get position 开发者_运维知识库of element relative to its parent. position() is suppose to do that but it looks like it doesn\'t.

I need to get position 开发者_运维知识库of element relative to its parent. position() is suppose to do that but it looks like it doesn't.

<!DOCTYPE html>
<html>
<head>
  <style>

  body{padding: 0px; margin: 0px;}
  div { margin-left: 200px; padding: 30px; border: 1px solid red;}
  p { margin: 0px; padding: 0px; border: 1px solid black }
  </style>
  <script src="http://code.jquery.com/jquery-1.5.js"></script>

    <script>
        $(document).ready(function() {

            var p = $("p.paragraf");
            var position = p.offset();
            $("p.zadnji").text( "left: " + position.left + ", top: " + position.top );

        });
    </script>  

</head>
<body>

<div class="container">
  <p class="paragraf">Hello</p>
</div>
<p class="zadnji"></p>

</body>
</html>

Result:

left: 231, top: 31

If p.paragraf is inside #container then #container should be parent to p.paragraf. If padding of #container is set to 30px, shouldn't both left and top position of p.paragraf be 30px?

I tried offset() but it gives the same result as position()


Aloha,

Add position: relative; to your container style

jsfiddle example

0

精彩评论

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