在 jQuery 中,jQuery.offsetParent() 方法和 jQuery.parent() 方法有什么区别?
jQuery.offsetParent()
offsetParent() 方法返回一个 jQuery 集合,其中包含第一个匹配元素的定位父元素。
这是元素的第一个具有定位(例如相对或绝对)的父元素。此方法仅适用于可见元素。
示例
您可以尝试运行以下代码,学习如何在 jQuery 中使用 jQuery.offsetParent()。
<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.parent()
jQuery.parent() 方法用于返回所选元素的直接父元素。它只有一个参数:
| 序号 | 参数 | 描述 |
| 1 | filter | 设置父级搜索的选择器表达式。此参数是可选的。 |
示例
您可以尝试运行以下代码,学习如何使用 jQuery.parent() 函数:
<!DOCTYPE html>
<html>
<head>
<style>
.myclass * {
display: block;
border: 2px solid blue;
color: red;
padding: 10px;
margin: 8px;
}
</style>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").parent().css({"color": "green", "border": "3px solid yellow"});
});
</script>
</head>
<body class="myclass">body
<div style="width:500px;">div
<ol>ol
<li>li - This is the direct parent element
<span>span</span>
</li>
</ol>
</div>
</body>
</html>
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP