为什么我在jQuery的偏移和位置获得相同的值?

3gw*_*ain 6 jquery

我在段落标记内放置了一个跨度,现在位置顶部应显示为0,偏移量应显示一些其他值(需要从文档计算),但我在两者中得到相同的值...

我错了?

这是我的代码:

HTML:

<div></div>
<p>paragraph<span>span</span>paragraph</p>
Run Code Online (Sandbox Code Playgroud)

jQuery的:

$('span').click(function(){
console.log($(this).position().top,$(this).offset().top)
})

CSS:

p{
  color:green;
}

span{
  color:red;
}

div{
  height:100px;
  border:2px solid blue;
}
Run Code Online (Sandbox Code Playgroud)

jsfiddle在这里

Jai*_*Jai 1

来自docs

.position()方法允许我们检索元素的当前位置relative to the offset parent

将 this 与.offset(), which进行对比retrieves the current position relative to the document

当将一个新元素定位在另一个元素附近且位于同一包含 DOM 元素内时,.position() 更有用。

如果我们谈论您的场景,那么:

目前,两者.position()都有.offset()相同的父级,它们将获得文档的偏移位置。

现在,如果您在 css 类中再添加一个属性,<p> position:relative;您就可以发现差异。

简而言之:

.offset().top将从文档中获取顶部。

.position().top将从相对父级获取顶部。(如果父级相对设置)

您可以在这里找到差异:http://jsfiddle.net/BhsrS/1/

检查小提琴:http://jsfiddle.net/BhsrS/1/