javascript - jQuery偏移量和位置方法之间有什么区别吗

标签 javascript jquery html css

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

HTML:

<!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,console,output

最佳答案

来自 .offset() 的 jQuery 文档:

The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is more useful.

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

关于javascript - jQuery偏移量和位置方法之间有什么区别吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23457639/

相关文章:

javascript - 拼接第三个参数是否接受任何值?

javascript - 按下按钮时更改 li 元素类,并在该 css 类中更改背景颜色

javascript - JAVASCRIPT音频应用程序:按钮不会根据设备而改变

javascript - jquery 函数输入单选 onchange

javascript - 向下滚动时如何缩小 Logo 大小?

java - jersey 2.x Moxy json 不支持 POJO 列表

javascript - JavaScript 中的条件

javascript - 如何使用 jQuery 启用禁用字段?

javascript - 如何在 AngularJS ng-include 中获取调用 onload 的元素

javascript - 将元素加载到每个容器时遇到问题