jQuery中position()和offset()的区别是什么

jQuery中position()和offset()的区别是什么

两个jQueryUI方法都返回包含顶部和左侧位置的整数坐标属性的对象。顶部和左侧坐标的位置是以像素为单位返回的。这两个函数都只适用于可见元素,而不是隐藏元素。

示例:该示例给出了包含文本的方框的顶部和左侧坐标。

<!DOCTYPE html>
<html>
 
<head>
    <title>The difference between
      offset and position Method</title>
    <script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
    </script>
 
    <!-- jQuery code to show the method -->
    <script>
        /* code for position */
        (document).ready(function() {
            ("#position").click(function() {
                var Geek = ("#testDiv").position();
                alert("Top : " + Geek.top +
                    " Left : " + Geek.left);
            });
 
            /* code for offset */
            ("#offset").click(function() {
                var Geek = $("#testDiv").offset();
                alert("Top : " + Geek.top +
                    " Left : " + Geek.left);
            });
        });
    </script>
 
    <style>
        #container {
            width: 40%;
            min-height: 100px;
            padding: 20px;
            font-size: 25px;
            border: 2px solid green;
            font-weight: bold;
            color: green;
            background: gray;
            position: relative;
        }
        #testDiv {
            background: silver;
        }
        h1 {
            color: green;
        }
    </style>
</head>
 
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <b>offset() and position()</b>
        <div>
            <div id="container">
                <div id="testDiv">
                  Welcome to GeeksforGeeks
                </div>
            </div>
 
            <div style="height:10px"></div>
            <button id="offset">click for offset</button>
            <button id ="position">
                  click for position
            </button>
        </div>
    </center>
</body>
 
</html>
HTML

输出:

  • 在点击任何按钮之前。
    jQuery中position()和offset()的区别是什么?
  • 点击该按钮后。

jQuery中position()和offset()的区别是什么?

offset:

jQuery中position()和offset()的区别是什么?

position:

offset()和position()方法的区别:

offset()方法 position()方法
jQuery中的offset()方法返回HTML元素相对于文档的第一个位置。 jQuery中的position()方法返回HTML元素的当前位置,相对于其偏移的父元素。
jQuery UI offset()是相对于文档的。 jQuery UI position() 是相对于父元素的。
当你想把一个新的元素定位在另一个已经存在的元素上面时,最好使用jQuery offset()方法。 当你想把一个新元素定位在同一容器内的另一个DOM元素附近时,最好使用jQuery position()方法。
offset()方法主要用于拖放功能。 position()方法用于将一个元素相对于文档、窗口或其他元素(如鼠标或光标)定位。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册