开发者

JQuery('body').offset().top is off when using margin-top?

So, if I understand http://api.jquery.com/offset correctly, $('body').offset() should return the position where the body is located, relative to the document. So inserting a <p>-tag at those coordinates on the page should put it at the very position of the body tag. But that is not what happens!

I tried this in both Safari 5.0.5 and Firefox 3.6 and both cases, the alert says "8" and the <p>-tag ends up 8 pixels from the top of the page, whereas the body tag starts 100 pixels further down on the page, as can be seen if inspecting using e.g firebug.

<!doctype html>
<html>
<head></head>
<body>
  <div style="margin-top:100px;background:yellow;">
    <p>Hello World</p>
  </div>

  <script type="text/javascript"         src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
  </script>
  <script>
    alert(jQuery('body').offset().top);
    var myp = jQuery('<p>Top of body?</p>')
    myp.appendTo(jQuery('body'));
    myp.offset(jQuery('body').offset());
  </script>

</body>

开发者_Go百科

So the question is: how am I supposed to do this so that the <p>-tag ends up in the body, and not at the top of the page, using .offset()?


In most cases you'll find the body offset is equal to 0, that is because the body of the page is == you browsers viewport.

The reason Hello World is 100px down, is because you've applied a padding to it. Do you want your text "Top of body?" to appear below Hello World?..

If so, first give your div a class name (I've used hworld) and then append your var to it.

<div style="margin-top:100px;background:yellow;" class="hworld">

And:

myp.appendTo(jQuery('.hworld'));

Hope this helps...


There must be something else interfering with your code.

It works fine in this fiddle I created: http://jsfiddle.net/jasongennaro/7sGGq/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜