如果我使用console.log($("#object").position().top)
,我得到一个数字,我认为这是"对象"的"顶部"
然而,如果我做document.getElementById("object").style.top = $("#object").position().top;
对象移动到另一个地方,(或者有时消失)
$("#object").position().top
回归的"顶端"是什么?编辑:哎呀,对不起,我本想写document.getElementById("object").style.top.
编辑2:澄清…
假设我有:
<div id=pie>...</div>
#pie
{
position:relative;
top:-50;
}
如果我做....console.log($(" #派").position直()上);console.log($(" #派").offset直()上),
将在控制台中打印的两个数字都不会是-50。
top
in:
-
javascript
-引用最上面的window
元素[doc] -
jQuery
:-
$.offset().top
-返回元素相对于页面顶部的偏移量[doc] -
$.position().top
-返回元素相对于第一个定位父元素的偏移量[doc]
-
例子:
window0
├...
└iframe1
├...
└iframe2
├...
└div1 style=position: relative top: * left: *
├...
└div2 style=position: absolute top: * left: *
├...
└div3 style /*no positioning*/
├...
└div4
> div4.top - returns window0
> div4.parent - returns iframe2
> $(div4).offset().top - returns the vertical distance from the top part of iframe2
> $(div4).position().top - returns the vertical distance from the top part of div2
在MDN,它解释说:
.top
-
"返回对窗口层次结构中最顶层窗口的引用。"
窗口在哪里。Parent属性返回当前窗口的直接父节点
窗口。Top返回窗口对象层次结构中最顶层的窗口。
从这个解释判断。.top
的结果将根据您的窗口层次结构而有所不同。
考虑.offset() http://api.jquery.com/offset/
.offset()方法允许我们检索元素相对于文档的当前位置。与此形成对比的是.position(),它检索相对于偏移的父元素的当前位置。
-
$(el).position().top
是到相对父节点的顶端距离。 -
$(el).offset().top
是到绝对父(窗口)的顶部距离。
还有:
#pie
{
position:relative;
top=-50;
}
包含2个错误。首先,CSS只使用:
来赋值。第二个问题:-50不作为单位。所以这对CSS来说没什么意义。
我猜你的意思是:
#pie
{
position:relative;
top:-50px; /* px or em or % or whatever you want.*/
}
这可能是为什么jQuery不能检索。top值的相对父:在这种情况下,它应该返回0或null。