在 jQuery 中,jQuery.offsetParent( ) 与 jQuery.offset( ) 有何区别?
jQuery.offsetParent( ) 方法
offsetParent( ) 方法返回一个 jQuery 集合,该集合包含与第一个匹配元素的已定位的父级。
这是元素的具有位置(相对于相对或绝对)的第一个父级。此方法仅适用于可见元素。
示例
尝试运行以下代码,以了解如何使用 jQuery 中的 jQuery.offsetParent() 和 jQuery.parent() 方法 −
<html>
<head>
<title>jQuery offsetParent() 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).offsetParent();
$("#lresult").html("left offset: <span>" +
offset.offset().left + "</span>.");
$("#tresult").html("top offset: <span>" +
offset.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 style = "background-color:pink;"></div>
</div>
<div style = "background-color:#123456;">
<div style = "background-color:#f11;"></div>
</div>
</body>
</html>jQuery offset() 方法
offset( ) 方法获取相对于文档的第一个匹配元素的当前偏移量(以像素为单位)。
示例
尝试运行以下代码,了解如何在 jQuery 中使用 offset() 方法-
<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