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

© . All rights reserved.