Jquery position() 包括保证金

Jquery position() include margin

如果我想在测量元素的宽度时包括边距,我可以调用 element.outerWidth(true); 但是,我找不到类似的方法来获取容器中元素的左偏移量,其中保证金包括在内。 element.position().left 不包括保证金。

我试过 element[0].getBoundingClientRect().left,这很有效,但是有类似的 jquery 调用吗?

编辑: 似乎上面的原生 javascript 调用也不给我保证金..

这是jQuery的.position()的一个限制,它有这个限制:

Note: jQuery does not support getting the position coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.

推荐的解决方案:

var position = $element.position();
x = position.left + parseInt($element.css('marginLeft'), 10);
y = position.top + parseInt($element.css('marginTop'), 10);

使用Jquery offset() 函数

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>offset demo</title>
  <style>
  p {
    margin-left: 10px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<p>Hello</p><p>2nd Paragraph</p>

<script>
var p = $( "p:last" );
var offset = p.offset();
p.html( "left: " + offset.left + ", top: " + offset.top );
</script>

</body>
</html>