当前位置: 首页 > 文档资料 > jQuery 入门教程 >

position()

优质
小牛编辑
118浏览
2023-12-01

描述 (Description)

position( )方法获取元素相对于其偏移父元素的顶部和左侧位置。

返回的对象包含两个Integer属性,top和left。 为了精确计算,请确保使用边距,边框和填充的像素值。 此方法仅适用于可见元素。

语法 (Syntax)

以下是使用此方法的简单语法 -

<i>selector</i>.position( )

参数 (Parameters)

以下是此方法使用的所有参数的说明 -

  • NA

例子 (Example)

以下是一个简单的例子,简单地显示了这种方法的用法 -

<html>
   <head>
      <title>The jQuery Example</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 position = $(this).position();
               $("#lresult").html("left position: <span>" + position.left + "</span>.");
               $("#tresult").html("top position: <span>" + position.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>
      <div  style = "background-color:pink;"></div>
      <div  style = "background-color:#123456;"></div>
      <div  style = "background-color:#f11;"></div>
   </body>
</html>