jQuery的offset和position方法有什么区别吗?

Is there any difference between jQuery offset and position method

本文关键字:什么 区别 方法 offset position jQuery      更新时间:2023-09-26

position和offset方法有什么区别吗?因为当我执行console.log()时,它们都返回一个对象,有两个属性top和left。我的疑问是,当我们使用offset和position方法时,或者它们都是做同样的事情。

:

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <meta charset="utf-8">
        <title>Difference between jQuery position and offset method</title>
    </head>
    <body>
        <div class='box'></div>
        <button id='btnOne'>click</button>
    </body>
</html>
CSS

:

.box {
    width: 100px;
    height: 100px;
    background: lightgray;
    margin-bottom: 10px;
}
jQuery

:

$(function(){
    $('#btnOne').on('click', function(){
        var offset = $('.box').offset();
        var position = $('.box').position();
        console.log(offset, position);
    });
});

,这里是jsbin链接http://jsbin.com/qibov/1/edit?html, css, js、控制台、输出

来自.offset()的jQuery文档:

.offset()方法允许我们检索元素相对于文档的当前位置。与.position()相比,.position()检索相对于偏移的父节点的当前位置。当为了全局操作(特别是为了实现拖放)而将新元素定位在现有元素之上时,.offset()更有用。

https://api.jquery.com/offset/

我认为Offset() 从屏幕顶部/左侧测量, Position()从父母的顶部/左侧测量。(我可能错了)

CSS

.box{ width: 100px; height: 100px; background: lightgray; margin-bottom: 10px; }
#cntnr{position: absolute; top: 100px; left: 100px;}  


<div id="cntnr"> <div class='box'></div> </div> <button id='btnOne'>click</button>

JavaScript

//same
结果

Object { top=100, left=100} Object { top=0, left=0}

.box放入容器中不会改变position,但会改变offset;