开发者

offset() values after replacing html content

I have a div acting as a wrapper that contains a开发者_如何学编程lmost the whole DOM (From body to /body) of a website. If I get the offset() of one of the elements when document is ready everything is ok but after a replacement $('#wrapper').html(newContent) the offset is 0.

Any hints?


If #wrapper is your content wrapper, then you're essentially swapping out your whole content with a new DOM subtree. That means that any element that was inside your #wrapper is now not part of the DOM anymore. The following code illustrates your problem:

$.ready(function() {
  var elem = $('#somediv'),
      wrapper = $('#wrapper'),
      newContent = '<div>...</div>';

  alert(elem.offset().top); // displays the correct offset

  wrapper.html(newContent); // swaps out the contents of #wrapper, destroys #somediv

  alert(elem.offset().top); // displays 0, because `elem` is not inside #wrapper anymore
});

A working example can be seen here: snippet@jsfiddle

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜