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
广告

© . All rights reserved.