无涯教程-jQuery - offsetParent( )方法函数

60 阅读1分钟

OffsetParent()方法返回具有第一个匹配元素的定位父元素的jQuery集合。

这是具有位置的元素的第一个父元素(如相对或绝对)。此方法仅适用于可见元素。

offsetParent( ) - 语法

selector.offsetParent( )

offsetParent( ) - 示例

下面是一个简单的示例,展示了这个方法-的用法

<html>
   <head>
      <title>The jQuery 举例</title>
      <script type="text/javascript" 
         src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
      </script>
      
      <script type="text/javascript" language="javascript">
         $(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>

这将产生以下结果-

参考链接

www.learnfk.com/jquery/css-…