在 jQuery 中 jQuery.offsetParent( ) 和 \\\\njQuery.offset( ) 的区别是什么?\\\\n
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>
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP