HTML - DOM Style 物件 position 屬性



HTML DOM Style 物件的 **position** 屬性設定或返回用於任何元素的定位方法型別。

語法

設定 position 屬性
object.style.position= "static | absolute | fixed | relative | sticky | initial | inherit";
獲取 position 屬性
object.style.position;

屬性值

描述
static 這是預設值,其中元素按文件流中出現的順序呈現。
absolute 用於相對於其第一個定位祖先元素定位元素。
fixed 用於相對於瀏覽器視窗定位元素。
relative 用於相對於正常位置定位元素,即“top:20”表示在元素的頂部位置新增 20 畫素。
sticky 用於根據使用者的滾動位置定位元素。預設情況下,它設定為 relative,並根據滾動位置在 relative 和 fixed 之間切換。
initial 用於將此屬性設定為其預設值。
inherit 用於繼承其父元素的屬性。

返回值

它返回一個字串值,表示元素的 position 型別。

HTML DOM Style 物件“position”屬性的示例

以下示例將不同的 position 屬性值設定為 id 為 **position** 的 div 元素。

將 position 值設定為“absolute”和“sticky”

以下示例將 position 屬性設定為 **absolute** 和 **sticky**。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object position Property
    </title>
    <style>
        #position {
            padding: 50px;
            height: 200px;
            width: 200px;
            position: static; 
            top: 120px; 
            left: 50px;
            border: 2px solid #04af2f;
            background-color: azure;
            }
    </style>
</head>
<body>
    <p>
        Click to set position property.
    </p>
    <button onclick="fun()">Absolute</button>    
    <button onclick="funTwo()">Sticky</button>
    <br><br><br>
    <div id="position">
        <p>Hello Everyone</p>
        <p>Welcome to Tutorials Point.</p>
    </div>
    <script>
        function fun() {
            document.getElementById("position")
                .style.position= "absolute";
        }  
        function funTwo() {
            document.getElementById("position")
                .style.position= "sticky";
        }        
    </script>
</body>
</html>

將 position 值設定為“relative”和“fixed”

以下示例將 position 屬性設定為 **relative** 和 **fixed**。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object position Property
    </title>
    <style>
        #position {
            padding: 50px;
            height: 200px;
            width: 200px;
            position: static; 
            top: 120px; 
            left: 50px;
            border: 2px solid #04af2f;
            background-color: azure;
            }
    </style>
</head>
<body>
    <p>
        Click to set position property.
    </p>
    <button onclick="fun()">Relative</button>    
    <button onclick="funTwo()">Fixed</button>
    <br><br><br>
    <div id="position">
        <p>Hello Everyone</p>
        <p>Welcome to Tutorials Point.</p>
    </div>
    <script>
        function fun() {
            document.getElementById("position")
                .style.position = "relative";
        }
        function funTwo() {
            document.getElementById("position")
                .style.position = "fixed";
        }         
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
position 是 1 是 12 是 1 是 1 是 4
html_dom_style_object_reference.htm
廣告