Let’s first look at the definitions of these two methods.
offset():
Get the relative offset of the matching element in the current viewport.
The returned object contains two integer properties: top and left. This method only works on visible elements.
position():
Get the offset of the matching element relative to the parent element.
The returned object contains two integer properties: top and left. For accurate calculations, use pixel units for filler, border, and fill properties. This method only works on visible elements.
Is it really that simple? Practice brings true knowledge.
First, let’s take a look at how position() is obtained in the jquery framework source code:
// Get *real* offsetParent
var offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= num( this, 'marginTop' );
offset.left -= num( this, 'marginLeft' );
// Add offsetParent borders
parentOffset.top = num( offsetParent, 'borderTopWidth' );
parentOffset.left = num( offsetParent, 'borderLeftWidth' );
// Subtract the two offsets
results = {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
Click on the page below to test the difference between the two:
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn