jQuery 中的 position() 和 offset() 有什么区别?
jQueryUI 方法都返回包含顶部和左侧位置的整数坐标属性的对象。顶部和左侧坐标的位置以像素为单位返回。这两个函数仅应用于可见元素,而不应用于隐藏元素。
示例:该示例给出了包含文本的框的顶部和左侧坐标。
The difference between
offset and position Method
GeeksforGeeks
offset() and position()
Welcome to GeeksforGeeks
输出:
- 在单击任何按钮之前:
- 点击按钮后:
offset() 和 position() 方法的区别:
offset() Method | position() Method |
---|---|
The offset() method in jQuery returns the first found position of HTML element with respect to the document. | The position() method in jQuery returns the current position of HTML element with respect to its offset parent. |
The jQuery UI offset() is relative to the document. | The jQuery UI position() is relative to the parent element. |
When you want to position a new element on top of another one which is already existing, its better to use the jQuery offset() method. | When you want to position a new element near another DOM element within the same container, its better to use jQuery position() method. |
The offset() method is mostly used in drag-and-drop functions. | The position() method is used to position an element relative to document, window or other elements like mouse or cursor. |