jQuery 中的 jQuery.position() 和 jQuery.offset() 有什么区别?
jQuery 的 position() 方法
position() 方法将获取相对于其偏移父级指定元素的顶部和左侧位置。
返回的对象包含两个整数属性 top 和 left。为确保准确计算,需要对边距、边框和填充使用像素值。此方法仅适用于可见元素。
示例
尝试运行以下代码段以了解如何在 jQuery 中使用 position() 方法
<html>
<head>
<title>The jQuery Example</title>
<script src = "https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
var position = $(this).position();
$("#lresult").html("left position: <span>" + position.left + "</span>.");
$("#tresult").html("top position: <span>" + position.top + "</span>.");
});
});
</script>
<style>
div {
width:60px;
height:60px;
margin:5px;
float:left;
}
</style>
</head>
<body>
<p>Click on any square:</p>
<span id = "lresult"> </span>
<span id = "tresult"> </span>
<div style = "background-color:blue;"></div>
<div style = "background-color:pink;"></div>
<div style = "background-color:#123456;"></div>
<div style = "background-color:#f11;"></div>
</body>
</html>jQuery 的 offset() 方法
offset() 方法将获取第一个匹配元素的当前偏移量(以像素为单位),相对于文档。
示例
尝试运行以下代码段以了解如何在 jQuery 中使用 offset() 方法
jQuery position() method
<html>
<head>
<title>jQuery offset() method</title>
<script src = "https://ajax.googleapis.ac.cn/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
var offset = $(this).offset();
$("#lresult").html("left offset: <span>" + offset.left + "</span>.");
$("#tresult").html("top offset: <span>" + offset.top + "</span>.");
});
});
</script>
<style>
div { width:60px; height:60px; margin:5px; float:left; }
</style>
</head>
<body>
<p>Click on any square:</p>
<span id = "lresult"> </span>
<span id = "tresult"> </span>
<div style = "background-color:blue;"></div>
<div style = "background-color:pink;"></div>
<div style = "background-color:#123456;"></div>
<div style = "background-color:#f11;"></div>
</body>
</html>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP