HTML - DOM樣式物件 left 屬性



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

語法

設定 left 屬性
object.style.left= "auto | length | percentage | initial | inherit";
獲取 left 屬性
object.style.left;

屬性值

描述
auto 這是預設值,讓瀏覽器設定 left 屬性值。
length 它以長度單位指定左值,可以是正值或負值。
percentage 它以父元素寬度的百分比值指定左值。
initial 用於將此屬性設定為其預設值。
inherit 用於繼承其父元素的屬性。

返回值

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

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

以下示例設定 p 和 div 元素的 left 屬性。

設定 p 元素的左位置

以下示例使用長度和百分比值設定 **p** 元素的 left 屬性。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object left Property
    </title>
    <style>
        #left {
            position: absolute;
        }
    </style>
</head>
<body>
    <p>
        Click to try different left property values.
    </p>
    <button onclick="fun()">Set Left in length</button>
    <button onclick="funTwo()">Set Left in %</button>    
    <br>
    <p id="left">
        Welcome to Tutorials Point.
    </p>
    <script>
        function fun() {
            document.getElementById("left")
                .style.left = "250px";
        }
        function funTwo() {
            document.getElementById("left")
                .style.left = "30%";
        }        
    </script>
</body>
</html>

設定 div 元素的左位置

以下示例設定 **div** 元素的 left 屬性。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object left Property
    </title>
    <style>
        #left {
            position: absolute;
        }
        #left div {
            width: 40px;
            height: 40px;
        }
    </style>
</head>
<body>
    <p>
        Click to try different left property values.
    </p>
    <button onclick="fun()">Set Left in length</button>
    <button onclick="funTwo()">Set Left in %</button>    
    <br><br>
    <div id="left">
        <div style="background-color: #04af2f;"></div>
    </div>
    <script>
        function fun() {
            document.getElementById("left")
                .style.left = "250px";
        }
        function funTwo() {
            document.getElementById("left")
                .style.left = "30%";
        }        
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
left 是 1 是 12 是 1 是 1 是 5
html_dom_style_object_reference.htm
廣告