javascript Jquery position() 包含边距

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31114656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:17:54  来源:igfitidea点击:

Jquery position() include margin

javascriptjqueryposition

提问by user1506145

If I want to include the margin when measuring the width of an element I may call element.outerWidth(true);However, I can't find a similar way to get the left offset of an element in a container, where the margin is included. element.position().leftdoesn't include margin.

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

I've tried element[0].getBoundingClientRect().left, and that works but is there a similar jquery call?

我已经尝试过了element[0].getBoundingClientRect().left,并且有效,但是是否有类似的 jquery 调用?

EDIT: It seems that the native javascript call above doesn't give me the margin either..

编辑:上面的原生 javascript 调用似乎也没有给我余量。

回答by Philip Dernovoy

This is a limitation of jQuery's .position(), which has this limitation:

这是 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.

注意:jQuery 不支持获取隐藏元素的位置坐标,也不支持在 body 元素上设置边框、边距或填充。

Recommended solution:

推荐解决方案:

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

回答by Payer Ahammed

Use Jquery offset() function

使用 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>