jQuery中的jQuery.offsetParent()和jQuery.parent()方法有什么区别?
jQuery.offsetParent()
该offsetParent()方法返回一个jQuery集合,该集合具有第一个匹配元素的父元素。
这是具有位置(相对或绝对)的元素的第一个父级。此方法仅适用于可见元素。
示例
您可以尝试运行以下代码以了解如何在jQuery中使用jQuery.offsetParent():
<html>
<head>
<title>jQuery offsetParent() method</title>
<script src = "https://cdn.staticfile.org/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()方法用于返回所选元素的直接父元素。它只有一个参数,
示例
您可以尝试运行以下代码,以了解如何使用jQuery.parent()函数,
<!DOCTYPE html>
<html>
<head>
<style>
.myclass * {
display: block;
border: 2px solid blue;
color: red;
padding: 10px;
margin: 8px;
}
</style>
<script src="https://cdn.staticfile.org/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>