HTML - DOM Style 物件 width 屬性



HTML DOM Style 物件**width**屬性設定或返回元素的寬度。此屬性僅適用於塊級元素或具有絕對或固定位置的元素。

語法

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

屬性值

描述
auto 這是預設值,它允許瀏覽器設定寬度值。
長度 它以長度值設定寬度。
百分比 它以父元素的百分比設定寬度。
initial 它用於將此屬性設定為其預設值。
inherit 它用於繼承其父元素的屬性。

返回值

它返回一個字串值,表示元素的寬度。

HTML DOM Style 物件“width”屬性示例

以下示例設定並獲取 div 元素的寬度值。

設定 div 元素的 width 屬性

以下示例使用長度和百分比值設定 div 元素的寬度。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object width Property
    </title>
    <style>
        #width {
            background-color: #04af2f;
            color: whitesmoke;
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <p>
        Click to set width property.
    </p>
    <button onclick="funTwo()">
        Set Width
    </button>
    <button onclick="funThree()">
        Set Width %
    </button>
    <br><br>
    <p id="width">
        JavaScript is a lightweight, interpreted 
        programming language. It is commonly used 
        to create dynamic and interactive elements 
        in web applications.
    </p>
    <script>
        function funTwo() {
            document.getElementById("width")
                .style.width = "250px";
        }
        function funThree() {
            document.getElementById("width")
                .style.width = "30%";
        }
    </script>
</body>
</html>

獲取 div 元素的 width 值

以下示例獲取 div 元素的寬度值。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM Style Object width Property
    </title>
    <style>
        #width {
            background-color: #04af2f;
            color: whitesmoke;
            border: 1px solid black;
        }
    </style>
</head>
<body>
    <p>
        Click to Get width values.
    </p>
    <button onclick="funTwo()">
        Get Width
    </button>
    <button onclick="funThree()">
        Get Width %
    </button>
    <br><br>
    <p id="res"></p>
    <p id="width">
        JavaScript is a lightweight, interpreted 
        programming language. It is commonly used 
        to create dynamic and interactive elements 
        in web applications.
    </p>
    <script>
        function funTwo() {
            let x=document.getElementById("width")
                .style.width = "250px";
            document.getElementById("res")
                .innerHTML="Width :" +x
        }
        function funThree() {
            let x=document.getElementById("width")
                .style.width = "30%";
            document.getElementById("res")
                .innerHTML="Width :" +x
        }
    </script>
</body>
</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
width 是 1 是 12 是 1 是 1 是 3.5
html_dom_style_object_reference.htm
廣告