.offset()的用法

 

offset用法可以用來讀取或設定現在這個元素的位置,如下範例為讀取位置

.offset()範例

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                var x = $("p").offset();
                $("#message").empty().append("Top: " + x.top + " Left: " + x.left);
            });
        });
    </script>
</head>
<body>
    <p>This is a paragraph.</p>
    <button>Return the offset coordinates of the p element</button>
    <div id="message">
    </div>
</body>
</html>

其.offset()回傳回來的就是一個coordinates的物件,如Object {top: 16, left: 8},

其中物件裡的top屬性代表往下位移了16個單位,left屬性代表往右位移了8個單位。

 

設定位置可有兩種方式,分別為.offset( coordinates )、.offset( function )

.offset( coordinates ) or .offset( object )範例

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").offset({ top: 200, left: 200 });
            });
        });
    </script>
</head>
<body>

    <p>This is a paragraph.</p>

    <button>Set the offset coordinates of the p element</button>

</body>
</html>

.offset( function )範例

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                $("p").offset(function (index, coordinates) {
                    newPos = new Object();
                    newPos.left = coordinates.left + 100;
                    newPos.top = coordinates.top + 100;
                    return newPos;
                });
            });
        });
    </script>
</head>
<body>
    <p>This is a paragraph.</p>
    <button>Set offset coordinates of the p element</button>
</body>
</html>

 

參考資料:

.offset()

jQuery offset() Method