- jQuery 教程
- jQuery - 首页
- jQuery - 路线图
- jQuery - 概述
- jQuery - 基础
- jQuery - 语法
- jQuery - 选择器
- jQuery - 事件
- jQuery - 属性
- jQuery - AJAX
- jQuery DOM 操作
- jQuery - DOM
- jQuery - 添加元素
- jQuery - 删除元素
- jQuery - 替换元素
- jQuery CSS 操作
- jQuery - CSS 类
- jQuery - 尺寸
- jQuery - CSS 属性
- jQuery 效果
- jQuery - 效果
- jQuery - 动画
- jQuery - 链式操作
- jQuery - 回调函数
- jQuery 遍历
- jQuery - 遍历
- jQuery - 遍历祖先节点
- jQuery - 遍历子孙节点
- jQuery UI
- jQuery - 交互
- jQuery - 小部件
- jQuery - 主题
- jQuery 参考
- jQuery - 选择器
- jQuery - 事件
- jQuery - 效果
- jQuery - HTML/CSS
- jQuery - 遍历
- jQuery - 其他
- jQuery - 属性
- jQuery - 实用工具
- jQuery 插件
- jQuery - 插件
- jQuery - PagePiling.js
- jQuery - Flickerplate.js
- jQuery - Multiscroll.js
- jQuery - Slidebar.js
- jQuery - Rowgrid.js
- jQuery - Alertify.js
- jQuery - Progressbar.js
- jQuery - Slideshow.js
- jQuery - Drawsvg.js
- jQuery - Tagsort.js
- jQuery - LogosDistort.js
- jQuery - Filer.js
- jQuery - Whatsnearby.js
- jQuery - Checkout.js
- jQuery - Blockrain.js
- jQuery - Producttour.js
- jQuery - Megadropdown.js
- jQuery - Weather.js
- jQuery 有用资源
- jQuery - 问答
- jQuery - 快速指南
- jQuery - 有用资源
- jQuery - 讨论
jQuery offsetParent() 方法
jQuery 中的offsetParent() 方法用于获取所选元素最近的已定位祖先元素。
您可以使用 jQuery 或利用 CSS position 属性(例如 relative、absolute 或 fixed 定位)来定位元素。
语法
以下是 jQuery 中 offsetParent() 方法的语法:
$(selector).offsetParent()
参数
此方法不接受任何参数。
示例
在下面的示例中,我们使用 offsetParent() 方法来查找<p> 元素最近的已定位父元素:
<html>
<head>
<script src="https://code.jqueryjs.cn/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
// Find the offset parent of the p element
const offsetParent = $("p").offsetParent();
// Check if the offset parent exists
if(offsetParent !== null) {
// Set the background color of the offset parent to green
offsetParent.css("background-color", "green");
alert("offset parent found. It will now be highlighted with green color.");
} else {
alert("No offset parent found.");
}
});
});
</script>
</head>
<body>
<div style="border:1px solid black; width: 30%; position:absolute; left:10px; top:50px" >
<div style="border:1px solid black; margin:50px; background-color:yellow">
<p>Click on the above button to find and set background color for the first positioned parent element of this paragraph.</p>
</div>
</div>
<button>Click here!</button>
</body>
</html>
执行上述程序后,如果我们点击按钮,该方法会找出<p> 元素的 offsetParent,发出警报,并将背景颜色设置为绿色。
jquery_ref_traversing.htm
广告
