HTML - DOM樣式物件 top 屬性



HTML DOM 樣式物件 **top** 屬性設定或返回**已定位**元素的頂部位置,包括邊距、邊框、填充和捲軸。

語法

以下是獲取或設定 top 屬性的語法。

設定 top 屬性

object.style.top= "auto | length | percentage | initial | inherit";

獲取 top 屬性

object.style.top;

屬性值

描述
auto 這是預設值,讓瀏覽器指定頂部位置。
長度 它以長度單位指定頂部位置,允許負值。
百分比 它以父元素高度的百分比指定頂部位置。
initial 用於將此屬性設定為其預設值。
inherit 用於繼承其父元素的屬性。

返回值

它返回一個字串值,表示已定位元素的頂部位置。

HTML DOM 樣式物件“top”屬性示例

以下示例設定 p 和 div 元素的頂部位置。

為 p 元素設定 top 屬性

以下示例使用長度和百分比值設定 p 元素的頂部位置。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object top Property
    </title>
    <style>
        #top {
            position: absolute;
        }
    </style>
</head>
<body>
    <p>
        Click to set the top position.
    </p>
    <button onclick="fun()">
        Set Top position
    </button>
    <button onclick="funTwo()">
        Set Top %
    </button>
    <p id="top">
        Welcome To Tutorials Point. 
    </p>
    <script>
        function fun() {
            document.getElementById("top")
                .style.top = "150px";
        }
        function funTwo() {
            document.getElementById("top")
                .style.top = "40%";
        }
    </script>
</body>
</html>

為 div 元素設定 top 屬性

以下示例使用負長度值設定 div 元素的頂部位置。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object top Property
    </title>
    <style>
        #top {
            position: absolute;
        }
    </style>
</head>
<body>
    <p>
        Click to set the top position.
    </p>
    <button onclick="fun()">
        Set Top position
    </button>
    <div id="top">
        <p>
            Welcome To Tutorials Point.
        </p>
    </div>
    <script>
        function fun() {
            document.getElementById("top")
                .style.top = "-5px";
        }
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
top 是 1 是 12 是 1 是 1 是 6
html_dom_style_object_reference.htm
廣告