内容目录
offsetParent()函数用于查找离当前匹配元素最近的被定位的祖辈元素。
所谓"被定位的元素",就是元素的CSS position属性值为absolute、relative或fixed(只要不是默认的static即可)。
该函数属于jQuery对象(实例)。
语法
jQuery 1.2.6 新增该函数。
jQueryObject.offsetParent( )
返回值
offsetParent()函数的返回值为Object类型,返回包含离当前元素最近的"被定位"的祖辈元素的jQuery对象。
offsetParent()函数将从当前元素开始逐级向上查找符合条件的元素。如果在找到<html>元素之前没有符合条件的祖辈元素,则匹配<html>元素。
示例&说明
以下面这段HTML代码为例:
<div id="n1">
<div id="n2" style="position: relative;">
<div id="n3" style="position: relative;" ></div>
<div id="n4">
<div id="n5">
<p id="n6">CodePlayer</p>
</div>
</div>
</div>
</div>
<div id="n7" style="position: absolute;">
<div id="n8" style="position: relative;" >
<p id="n9">专注于编程开发技术分享</p>
</div>
</div>
<p id="n10">https://codeplayer.vip</p>
以下jQuery示例代码用于演示offsetParent()()函数的具体用法:
function w(html){
document.body.innerHTML += html;
}
//返回jQuery对象所有匹配元素的标识信息数组
//每个元素形如:"tagName"或"tagName#id"
function getTagsInfo($doms){
return $doms.map( function(){
return this.tagName + ( this.id ? "#" + this.id : "" );
} ).get();
}
// $("p") 匹配n6、n9、n10三个元素
// n6向上查找,找到被定位的祖辈元素n2
// n9向上查找,找到被定位的祖辈元素n8,只要找到了一个就不再继续向上查找
// n10向上查找,一直找到html标签之前都没有找到被定位的祖辈元素,因此匹配html
w( getTagsInfo( $("p").offsetParent() ) ); // DIV#n2,DIV#n8,HTML

0 条评论
撰写评论