了解偏移方法的 return 值

Understanding the offset method's return values

我在 HTML 文档中有一个带有 id="stimulus" 的元素。

当我在浏览器中打开此文档并使用浏览器的控制台调查 ​​#stimulus 的属性时,这是我看到的:

> $('#stimulus').offset()
< Object {top: 0, left: 0}
> $('#stimulus').css('top')
< "-155.761px"
> $('#stimulus').css('left')
< "253.087px"

我该如何解释? offset 中的 top 与使用 css 方法访问的 top 有何不同?

来自 offset() documentation, offset is from the top of the document; whereas top and left css properties are relative to the parent. Perhaps you wish to look at position() to get the offset relative to the offset parent.

jQuery 的 .offset() 方法 "returns the coordinates of the element relative to the document",而 .css() 方法 returns 通过 CSS 样式应用任何值。

http://api.jquery.com/offset/

偏移量是整个页面内的位置

css top 将相对于其最近定位的祖先放置元素。 该祖先可能位于页面中的任何位置,因此 offset 和 top 不匹配,除非没有定位的祖先

来自jQuery's .offset() documentation

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent.

.css() method abstracts the native CSSStyleDeclaration API, which returns the position relative to the parent element, but only if it is explicitly specified in CSS. So if you want that, then use .position()代替.offset().

演示

$(function() {
  var child = $('.child');

  console.log('offset: ', child.offset());
  console.log('position: ', child.position());
  console.log('css: ', {
    top: child.css('top'),
    left: child.css('left')
  });
});
html,
body {
  margin: 0;
  padding: 0;
}
.parent {
  position: absolute;
  top: 5px;
  left: 5px;
}
.child {
  position: absolute;
  top: 10px;
  left: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>

<div class="parent">
  <div class="child">Hello World</div>
</div>

您可能得到了不同的结果,因为 id="stimulus" 正在制作动画并且您在不同的帧中发送了 console.log。或者元素实际上是 "static" 并且有一些其他属性改变了他的 offset() 位置。

喜欢

console.log("Offset:", $('.test').offset()); // returns {top: 0, left: 0}
console.log("Top/Left:", $('.test').css('top'),  $('.test').css('left')); // returns -200px, -20px
.test{
  position: absolute;
  top: -200px;
  left: -20px;
  transform: translateY(200px) translateX(20px);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test"></div>