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